【问题标题】:Using python to replace strings with new strings in python使用python在python中用新字符串替换字符串
【发布时间】:2022-11-17 16:06:04
【问题描述】:

我得到了下面的代码进行测试,但它没有按预期方式工作。

请注意,我使用的是 MacM1 并使用 vscode 作为 IDE。

fin = open("file.txt", "rt")

#output file to write the result to
fout = open("out.txt", "wt")

#for each line in the input file
for line in fin:

    #read replace the string and write to output file
    fout.write(line.replace('old', 'new'))

#close input and output files
fin.close()
fout.close()

我已经准备好了 file.txt,里面有字符串,包括“old”。 运行程序后,新文件 out.txt 已创建,但它是空的。 Vscode 不显示错误所以我不知道在哪里修复它。 谢谢!

【问题讨论】:

  • 我猜 write 函数完全将那行从 fin 写入 fout,因此 fin 中的最后一行必须为空,因此您的输出也为空。尝试使用附加功能来修复此fout = open("out.txt", "a"),或者您可以将fout.write替换为fout.writelines
  • 你的代码对我来说很好用。您可以在循环中添加 print 语句,只是为了确保它正在运行。
  • @GautamChettiar——这是完全错误的。一旦文件打开,写入将始终追加。
  • 不好意思,是的,我刚刚检查过它对我也能正常工作
  • 这与 VSCode 或您在 macOS 上运行无关。除了您没有利用工作管理器范例这一事实之外,如果您的当前工​​作目录中存在 file.txt 并且您有权创建 out.txt,您的代码将可以正常工作。此外,没有理由一次一行地读取输入文件,除非它很大并且你有内存限制

标签: python


【解决方案1】:
  1. 您应该始终为 IO 使用上下文管理器。
  2. open"t" 不是必需的,因为 t 代表 text mode,这是默认值。
    # main.py
    with open("file.txt", "r") as fin, open("out.txt", "w") as fout:
        for line in fin.readlines(): # using for line in fin also works
            fout.write(line.replace("old", "new"))
    
    ❯ python3 main.py
    ❯ cat file.txt
    test old
    test                                                                                                                                            
    ❯ cat out.txt
    test new
    test    
    

【讨论】:

    【解决方案2】:

    除非您的输入文件很大,否则没有理由逐行读取它。以下内容就足够了:

    with open('file.txt') as fin, open('out.txt', 'w') as fout:
      fout.write(fin.read().replace('old', 'new'))
    

    【讨论】:

      猜你喜欢
      • 2016-09-17
      • 2014-10-12
      • 1970-01-01
      • 2012-11-17
      • 1970-01-01
      • 1970-01-01
      • 2012-04-23
      • 2014-07-08
      • 1970-01-01
      相关资源
      最近更新 更多