我正在打开一个文件,如果满足特定条件,打开另一个文件并将记录从第一个文件传输到第二个文件,然后从第一个文件中删除它们。下面的代码有效,但行f.truncate()
除外,它导致此帖子标题中的错误。谁能告诉我需要修改哪些才能使这项工作?
f = open(filename,"r")
d = f.readlines()
f.seek(0)
for i in d:
e = i.split(',')
if len(e) > 28:
with open(filename2, "a") as text_file:
text_file.write(i.encode('cp1252'))
text_file.close
f.truncate()
f.close()
答案 0 :(得分:4)
你必须打开第一个文件"r+"
才能读写,如下所示:
f = open(filename,"r+")
for line in f:
e = line.split(',')
if len(e) > 28:
with open(filename2, "a") as text_file:
text_file.write(line.encode('cp1252'))
f.seek(0)
f.truncate()
f.close()
我还使代码更有效率,因为它应该遍历行而不是将它们复制到一边。一种更有效的方法是:
with open(filename,"r+") as file1, open(filename2, "a") as file2:
for line in f:
if line.count(',') > 27:
file2.write(line.encode('cp1252'))
file1.truncate(0)
这样你就不会在每次迭代时重新打开文件,并且由于你没有使用拆分值,你可以只计算逗号(,
)并比较27而不是28。
仅删除复制的行
如果您只想删除复制的行而不是清空文件,除了将整个文件复制到内存或使用tempfile之外,您无其他办法。
这是通过复制到内存来实现的:
with open(filename,"r+") as file1, open(filename2, "a") as file2:
file_lines = file1.readlines()
file1.seek(0)
file1.truncate()
for line in file_lines:
if line.count(',') > 27:
file2.write(line.encode('cp1252'))
else:
file1.write(line)
如果您使用的是Python 3.X,请确保指定编码。
答案 1 :(得分:0)
将其视为读取file1,将其拆分为两个,并将这些部分写入file1和file2。我甚至不打扰truncate()
因为打开文件来截断它:
with open(filename1) as file1:
data = file1.readlines()
lines1 = []
lines2 = []
for line in data:
if len(line.split(",")) > 28:
lines2.append(line)
else:
lines1.append(line)
with open(filename1, "w", encoding='cp1252') as outfile: # Wipes out old contents
outfile.writelines(lines1)
with open(filename2, "w", encoding='cp1252') as outfile:
outfile.writelines(lines2)