0

当我尝试运行此脚本时,我收到此错误:

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)

编辑:由于我withopen消息中删除了错误更改为:

`open (C:\\path\\to\\\\file.txt, 'w') as outfile` :

SyntaxError : 无效的语法,下面有一个指针

编辑:这个问题很混乱。毕竟,我恢复with并修复了一些缩进。它工作得很好!

4

2 回答 2

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)
于 2013-07-11T14:05:56.490 回答
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)
于 2013-07-11T14:12:42.117 回答