Home > Back-end >  Question about python list comprehension and file reading
Question about python list comprehension and file reading

Time:10-08

Recently I was dealing with CSV files and tried to replace the NULL bytes in the CSV file to empty strings to make the CSV reader work. I referred to this answer but decided to do it in a different way.

The original solution is like this:

with open(file) as f:
    reader  = csv.reader(x.replace('\0','') for x in f)
    print([x for x in reader])

But I decide to do it like this:

with open(file) as f:
    for line in f:
        line.replace('\0','')
    f.seek(0)
    reader  = csv.reader(f)
    print([x for x in reader])

And my approach seemed not to work as the original one, I wonder why is that? Thank you for your time!

CodePudding user response:

Take a look at the official doc of the replace function in python:

str.replace(old, new[, count])
Return a copy of the string with all occurrences of substring old replaced by new. If the optional argument count is given, only the first count occurrences are replaced.

In your implementation, you are calling replace but not capturing the returned replaced line anywhere.

You could instead, replace the whole file and store it in another variable or, if it is large, perform your operation inside the for loop itself.

However, the reference implementation you showed before looks better: It uses a generator that will yield replaced lines as you need them, you should stick with that.

  • Related