Writelines()不写入

0 投票
4 回答
2472 浏览
提问于 2025-04-17 13:36

运行这段代码会生成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

你需要在 close 后面加一个 ()

fo.close()

另外,处理文件时,可以考虑使用 with 语句。

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。

撰写回答