【问题标题】:Replacing string in a file with a new string用新字符串替换文件中的字符串
【发布时间】:2017-09-04 06:40:29
【问题描述】:

我有一个文本文件中的字符串列表。弦是早晨,夜晚,太阳,月亮。我想要做的是用另一个字符串替换其中一个字符串。例如,我会输入上午来删除并用下午替换它。当字符串明显在列表中时,我收到一条错误消息“builtins.ValueError: list.remove(x): x not in list”。

def main():
    x = input("Enter a file name: ")
    file = open(x , "r+")
    y = input("Enter the string you want to replace: ")
    z = input("Enter the string you to replace it with: ")
    list = file.readlines()
    list.remove(y)
    list.append(z)
    file.write(list)
    print(file.read())

main()

如果有更好的方法来实现相同的结果,请告诉我。感谢您的帮助!

【问题讨论】:

  • 您的意思是在原地编辑文件而不创建另一个文件?
  • 首先,请不要调用您的变量list,因为list() 是一个内置函数。其次,list 中的字符串末尾有换行符'\n'。在尝试 remove 之前,您应该将它们脱掉。

标签: python python-3.x file replace


【解决方案1】:

这里有一些想法:

  • str.replace() 函数是替换字符串最简单的方法,s.replace(y, z)。

  • re.sub() 函数可让您搜索模式并替换为字符串:re.sub(y, z, s)。

  • fileinput 模块将允许您就地修改。

这是一种方法:

import fileinput
import re

with fileinput.input(files=('file1.txt', 'file2.txt'), inplace=True) as f:
    for line in f:
        print( re.sub(y, z, line) )

这里有另一个想法:

  • 无需逐行处理,只需将整个文件作为单个字符串读入,修复它,然后再写回。

例如:

import re

with open(filename) as f:
    s = f.read()
with open(filename, 'w') as f:
    s = re.sub(y, z, s)
    f.write(s)

【讨论】:

    【解决方案2】:

    也许您正在寻找 Python replace() 方法?

    str = file.readlines()
    str = str.replace(y, z) #this will replace substring y with z within the parent String str
    

    【讨论】:

      【解决方案3】:

      假设你的txt保存在src.txt:

      morning
      night
      sun
      moon
      

      windows下可以使用这个批处理脚本,保存在replace.bat:

      @echo off
      setlocal enabledelayedexpansion
      set filename=%1
      set oldstr=%2
      set newstr=%3
      
      for /f "usebackq" %%i in (%filename%) do (
          set str=%%i
          set replace=!str:%oldstr%=%newstr%!
          echo !replace!
      )
      

      用途:

      replace.bat src.txt morning afternoon > newsrc.txt
      

      或grepWin。

      使用sed 或gawk 可能更简单。

      sed -i "s/morning/afternoon/g" src.txt
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 2015-10-14
        • 1970-01-01
        • 2011-07-01
        • 2015-07-31
        • 1970-01-01
        • 2013-07-09
        • 1970-01-01
        • 1970-01-01
        相关资源
        最近更新 更多