为什么我的脚本没有写入文件?

时间:2017-02-14 23:16:50

标签: python python-3.x file-io

我编写了一个脚本来删除外语文本中的多余空格。当我在Windows命令提示符下执行脚本时,我没有收到任何错误。一切看起来都很完美。但是,我没有创建我在脚本中指定的输出文件,也没有修改输入文件。我尝试创建一个空白文档'corpus_1'供脚本写入。然后我尝试回写输入文件。无论哪种方式,指定的文件都保持不变。如何让我的脚本写入文件?我的代码中缺少什么?

def lettersWhitespace():

    replacements = {'  ':' ', 'c ':'c'}

    with open('C:\\Users\\Charles\\corpus.odt','w+') as infile, open('C:\\Users\\Charles\\corpus_1.odt', 'w') as outfile:
        for line in infile:
            for src, target in replacements.iteritems():
                line = line.replace(src, target)
            outfile.write(line)
编辑:我相信我发现了问题。看来我的第一行'def lettersWhitespace():'是多余的。如上所述,脚本定义了一个函数,但没有调用该函数。这听起来不错吗?

1 个答案:

答案 0 :(得分:1)

ww+都会截断文件。假设您有一个包含abc的文件(每个都在换行符中):

with open('testfile.txt', 'w') as f:
    f.write('a\nb\nc')

然后在r中打开它,您可以阅读文件:

with open('testfile.txt', 'r') as f:
    print(f.read())
# a
# b
# c

如果你在w+模式下打开它,它会被截断(空):

with open('testfile.txt', 'w+') as f:
    print(f.read())
# 

您可能希望从文件开头开始“非截断”读/写模式:r+(或者如果您希望文件句柄位于文件末尾:a+

with open('testfile.txt', 'r+') as outp, open('testfile.txt', 'r') as inp:
    for line in inp:
        line = line.replace('a', 'b')
        outp.write(line)

在您编写时修改文件:

with open('testfile.txt', 'r') as f:
    print(f.read())
# b
# b
# c

可以在this StackOverflow answer of @And中找到非常方便的文件模式摘要。

相关问题