在脚本中,我正在向文件写入行,但有些行可能是重复的。所以我创建了一个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
循环永远不会被执行。我可以通过在调试器中放置断点来验证这一点;该行代码只是被跳过并且函数退出。我什至从这个线程中阅读了这个答案并插入了代码cStringIO.OutputType.getvalue(f_temp)
,但这并没有解决我的问题。
我不知道为什么我不能读取和遍历我的类文件对象。