Writelines()不写入
运行这段代码会生成file2.txt这个文件,结果是文件是空的。(注意:file1.txt里面只有一些诗句。)为什么会这样呢?我该怎么做才能把数组a2的内容写入到文本文件里呢?
import copy
#Open input file, read it into an array, and remove the every other line.
f = open('file1.txt','r')
a1 = f.readlines()
a2 = copy.deepcopy(a1)
f.close
for n in range(len(a1)):
if n%2 == 0:
a2.remove(a1[n])
# Open output file and write array into it.
fo = open('file2.txt','w')
fo.writelines(a2)
fo.close
4 个回答
2
2
你知道吗,其实这样写会更好:
from itertools import islice
with open('input') as fin, open('output','w') as fout:
every_other = islice(fin, None, None, 2)
fout.writelines(every_other)
理由:
- 文件不会无缘无故地加载到内存中
islice
可以用来创建一个生成器,提取每隔一行的内容- 然后可以把这个生成器传给输出的
.writelines()
方法 with
语句(上下文管理器)会自动在之后关闭文件- 这样写(在我看来)更容易阅读和理解意图
0
'close' 是一个方法,也就是说,你应该用 fo.close() 来代替 fo.close。