【发布时间】:2018-07-18 07:27:20
【问题描述】:
在脚本中,我将行写入文件,但有些行可能是重复的。所以我创建了一个临时的cStringIO 类文件对象,我称之为“中间文件”。我先将这些行写入中间文件,删除重复项,然后写入真实文件。
所以我编写了一个简单的 for 循环来遍历中间文件中的每一行并删除所有重复项。
def remove_duplicates(f_temp, dir_out): # f_temp is the cStringIO object.
"""Function to remove duplicates from the intermediate file and write to physical file."""
lines_seen = set() # Define a set to hold lines already seen.
f_out = define_outputs(dir_out) # Create the real output file by calling function "define_outputs". Note: This function is not shown in my pasted code.
cStringIO.OutputType.getvalue(f_temp) # From: https://stackoverflow.com/a/40553378/8117081
for line in f_temp: # Iterate through the cStringIO file-like object.
line = compute_md5(line) # Function to compute the MD5 hash of each line. Note: This function is not shown in my pasted code.
if line not in lines_seen: # Not a duplicate line (based on MD5 hash, which is supposed to save memory).
f_out.write(line)
lines_seen.add(line)
f_out.close()
我的问题是for 循环永远不会被执行。我可以通过在调试器中放置断点来验证这一点;该行代码只是被跳过并且函数退出。我什至阅读了this answer from this thread 并插入了代码cStringIO.OutputType.getvalue(f_temp),但这并没有解决我的问题。
我不知道为什么我不能读取和遍历我的类文件对象。
【问题讨论】:
-
f_temp是文件对象吗?cStringIO.OutputType.getvalue(f_temp)...的目的是什么? -
@juanpa.arrivillaga 是的,它是一个类似文件的对象。显然,
cStringIO.OutputType.getvalue(f_temp)的目的是将cStringIO类文件对象转换为Output类型以便可以读取它。见this评论。