Python语法错误可能是缩进?

2024-06-16 04:56:22 发布

您现在位置:Python中文网/ 问答频道 /正文

当我尝试运行此脚本时,出现以下错误:

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,并修复了一些缩进。而且效果很好!你知道吗


Tags: topathimportosas错误dirwith
2条回答

看起来您的outfileinfile处于同一级别—这意味着在第一个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)

您使用上下文管理器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)

相关问题 更多 >