Python语法错误可能是缩进?

Python语法错误可能是缩进?,python,Python,当我尝试运行此脚本时,出现以下错误: 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 out

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

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)
编辑:自从我从
open
中删除了
with
后,消息错误变为:

`open (C:\\path\\to\\\\file.txt, 'w') as outfile` :
SyntaxError:下面的指针为的语法无效


编辑:这个问题让人很困惑。毕竟,我用恢复了
,并稍微修正了缩进。它工作得很好

您将上下文管理器
用于
,这意味着当您退出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)

看起来您的
outfile
infle
处于同一级别-这意味着在带有
块的第一个
末尾,
outfile
关闭,因此无法写入。将
infle
块缩进到
infle
块内

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)

对不起,你是对的,我会尽快编辑我的问题并更新错误。不需要抱歉。学习一些东西是最重要的。@LDN-5602如果你想将
用作
一起使用是必须的<使用
可以给您带来很多方便,所以不要删除它。哦,我明白了。虽然
with
不是经常用于像
with codec这样的东西。打开
?如果我不使用其他任何东西,保留它有什么意义。无论如何,我将在以后恢复它,以防万一。
使用。。。as
是Python中的一种语法。它充当上下文管理器。你必须这么做。我做了,显然问题出在别处。无论如何,谢谢你的反馈