Skip to main content
 首页 » 编程设计

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

2025年02月15日9qq号

我编写了一个脚本来删除外语文本中的多余空格。当我在 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():”是多余的。如所写,脚本正在定义一个函数,但不调用该函数。这听起来正确吗?

请您参考如下方法:

w 和w+ 都会截断文件。假设您有一个文件包含 a、b、c(每个都在换行符中):

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 中找到文件模式的非常方便的摘要。 .