当我尝试运行此脚本时,出现以下错误:
ValueError: I/O operation on closed file.
我检查了一些类似的问题和医生,但没有成功。虽然错误已经很清楚了,但我还是没能弄清楚。很明显我遗漏了什么。你知道吗
# -*- coding: utf-8 -*-
import os
import re
dirpath = 'path\\to\\dir'
filenames = os.listdir(dirpath)
nb = 0
open('path\\to\\dir\\file.txt', 'w') as outfile:
for fname in filenames:
nb = nb+1
print fname
print nb
currentfile = os.path.join(dirpath, fname)
open(currentfile) as infile:
for line in infile:
outfile.write(line)
编辑:由于我从open
中删除了with
,消息错误变为:
`open (C:\\path\\to\\\\file.txt, 'w') as outfile` :
SyntaxError : invalid syntax with a pointer underneath as
编辑:这个问题有很多困惑。毕竟,我恢复了with
,并修复了一些缩进。而且效果很好!你知道吗
看起来您的
outfile
与infile
处于同一级别—这意味着在第一个with
块的末尾,outfile
已关闭,因此无法写入。将infile
块缩进到infile
块中。你知道吗您可以在这里使用
fileinput
模块简化代码,使代码更清晰,更不容易出现错误的结果:您使用上下文管理器
with
,这意味着当您退出with作用域时,文件将被关闭。所以outfile
在你使用它的时候显然是关闭的。你知道吗相关问题 更多 >
编程相关推荐