Unable to remove blank strings from string list in Python

Viewed 26

I have several tab delimited text files I'm attempting to parse. I use the following code to copy the contents of the text files to a list. However, it looks like there are extra tabs in the document(s) that generate blank string elements ('').

def ParseTextFile():
gto_file = open('C:\\Users\\Owner\\Downloads\\1.txt', 'r')
result = [line.split('\t') for line in gto_file.readlines()]

if __name__ == '__main__':
ParseTextFile()

An example row from the text file(s) is below

AABC 91.094 1.000 0.424 0.576 0 42.415 57.585 0 69.3365 69.3741 69.3089 0

I've attempted to use a filter

result = list(filter(len, result))

I've attempted to use remove()

while ("" in result):
        result.remove("")

I've attempted using list comprehension

result = [i for i in test_list if i]

I've attempted join() and split()

result = ' '.join(test_list).split()

and I've tried len()

for i in result:
    if(len(i)==0):
        result.remove(i)

I don't receive any errors but the list is always returned with the blank strings. I'm relatively new to Python, so I feel like I may be missing something easy. If anyone can point me in the right direction, I would greatly appreciate it.

1 Answers

You could do try this:

result = ['./Compresses/convertToJPEG.py', '', 'dummmy/path']
result = [x for x in result if x != '']
print(result)
# prints ['./Compresses/convertToJPEG.py', 'dummmy/path']
Related