我正在将数据写入CSV文件,然后一旦完成,我将文件复制到另一个目录。
这都是循环,所以当第二次迭代开始时,它会从复制的文件中读取数据。
问题是在第二次迭代开始时文件仍在被复制,这会导致明显的问题。
在第二次迭代开始之前,我如何等待循环中的整个函数完成?它应该可以继续任何迭代次数。
for rule in substring_rules:
substring(rule)
功能:
def substring(rule, remove_rows=[]):
writer = csv.writer(open("%s%s" % (DZINE_DIR, f), "wb"))
from_column = rule.from_column
to_column = rule.to_column
reader = csv.reader(open("%s%s" % (OUTPUT_DIR, f)))
headers = reader.next()
index = 0
from_column_index = None
for head in headers:
if head == from_column:
from_column_index = index
index += 1
if to_column not in headers:
headers.append(to_column)
writer.writerow(headers)
row_index = 0
for row in reader:
if rule.get_rule_type_display() == "substring":
try:
string = rule.string.split(",")
new_value = string[0] + row[from_column_index] + string[1]
if from_column == to_column:
row[from_column_index] = new_value
else:
row.append(new_value)
except Exception, e:
print e
if row_index not in remove_rows:
writer.writerow(row)
row_index += 1
shutil.copyfile("%s%s" % (DZINE_DIR,f), "%s%s" % (OUTPUT_DIR, f))
答案 0 :(得分:0)
问题是您在复制之前没有将读取器的文件刷新到磁盘。 (当文件对象被垃圾收集时自动完成)
而不是
writer = csv.writer(open("%s%s" % (DZINE_DIR, f), "wb"))
...
shutil.copyfile("%s%s" % (DZINE_DIR,f), "%s%s" % (OUTPUT_DIR, f))
你应该写
wf = open("%s%s" % (DZINE_DIR, f), "wb")
writer = csv.writer(wf)
...
wf.close()
shutil.copyfile("%s%s" % (DZINE_DIR,f), "%s%s" % (OUTPUT_DIR, f))