如何解决 Python 代码中 file.close() 中的语法错误?

问题描述 投票:0回答:2

我正在尝试读取一个文本文件并在每一行执行两件事:

  • 显示在我的显示器上
  • 创建备份副本..

之前的代码可以工作,但 Python 在我的显示器上显示垃圾

然后我尝试了这段代码,但它不起作用。它抱怨 file.close() 语句上存在语法错误。

file = open ('C:\ASlog.txt', 'r')
output = open('C:\ASlogOUT.txt', 'w')

for line in file:
   print(str(line))
   output.write(line

file.close()
output.close()
python file sequential
2个回答
2
投票

您之前的行中缺少一个括号

output.write(line

应该是

output.write(line)

0
投票

如果您是 Python 新手,尤其是 3.3,您应该使用

with
,它会自动关闭文件:

with open('input') as fin, open('output', 'w') as fout:
    fout.writelines(fin) # loop only if you need to do something else

在这种情况下哪个写得更好:

import shutil
shutil.copyfile('input filename', 'output filename')

因此,您的完整示例将用于显示到屏幕并将行写入文件:

with open('input') as fin, open('output', 'w') as fout:
    for line in fin:
        print(line)
        fout.write(line)
© www.soinside.com 2019 - 2025. All rights reserved.