当我尝试运行此脚本时,我收到此错误:
ValueError:关闭文件的I / O操作。
我查了一些类似的问题和文档,但没有成功。虽然错误很清楚,但我还没能弄明白。显然我错过了一些东西。
# -*- 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)
修改:由于我从with
删除了open
,因此邮件错误更改为:
`open (C:\\path\\to\\\\file.txt, 'w') as outfile` :
SyntaxError:语法无效,下面带有指针
编辑:对这个问题很困惑。毕竟,我恢复了with
并且我修改了一些缩进。它工作得很好!
答案 0 :(得分:0)
您使用上下文管理器with
,这意味着退出with范围时文件将被关闭。因此,outfile
在使用时显然已关闭。
with 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)
with open(currentfile) as infile:
for line in infile:
outfile.write(line)
答案 1 :(得分:0)
您的outfile
似乎与infile
处于同一级别 - 这意味着在第一个with
区块结束时,outfile
已关闭,因此可以'写到。将infile
块缩进为 infile
块。
with open('output', 'w') as outfile:
for a in b:
with open('input') as infile:
...
...
您可以使用fileinput
模块在此处简化代码,并使代码更清晰,更不容易出现错误结果:
import fileinput
from contextlib import closing
import os
with closing(fileinput.input(os.listdir(dirpath))) as fin, open('output', 'w') as fout:
fout.writelines(fin)