关于 python 列表理解和文件读取的问题
Question about python list comprehension and file reading
最近我在处理 CSV 文件,并试图将 CSV 文件中的 NULL 字节替换为空字符串以使 CSV reader 工作。我提到了这个 answer 但决定以不同的方式进行。
原解是这样的:
with open(file) as f:
reader = csv.reader(x.replace('[=11=]','') for x in f)
print([x for x in reader])
但我决定这样做:
with open(file) as f:
for line in f:
line.replace('[=12=]','')
f.seek(0)
reader = csv.reader(f)
print([x for x in reader])
而且我的方法好像和原来的方法不一样,请问这是为什么?
感谢您的宝贵时间!
看看python中replace
函数的官方文档:
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.
在您的实现中,您正在调用替换但未在任何地方捕获返回的替换行。
您可以改为替换整个文件并将其存储在另一个变量中,或者,如果它很大,则在 for 循环本身内执行您的操作。
但是,您之前展示的参考实现看起来更好:它使用一个生成器,可以根据需要生成替换行,您应该坚持使用它。
最近我在处理 CSV 文件,并试图将 CSV 文件中的 NULL 字节替换为空字符串以使 CSV reader 工作。我提到了这个 answer 但决定以不同的方式进行。
原解是这样的:
with open(file) as f:
reader = csv.reader(x.replace('[=11=]','') for x in f)
print([x for x in reader])
但我决定这样做:
with open(file) as f:
for line in f:
line.replace('[=12=]','')
f.seek(0)
reader = csv.reader(f)
print([x for x in reader])
而且我的方法好像和原来的方法不一样,请问这是为什么? 感谢您的宝贵时间!
看看python中replace
函数的官方文档:
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.
在您的实现中,您正在调用替换但未在任何地方捕获返回的替换行。
您可以改为替换整个文件并将其存储在另一个变量中,或者,如果它很大,则在 for 循环本身内执行您的操作。
但是,您之前展示的参考实现看起来更好:它使用一个生成器,可以根据需要生成替换行,您应该坚持使用它。