python - 文件中的通用字符串替换

标签 python

我正在寻找一种替换文件中字符串的通用方法。 我有一个文件(可以是 .txt.bat.xml ) 我想替换特定的字符串,例如"ABC" ,通过另一个字符串,例如"EFG"

我已经尝试过这个:

def replace_in_file(file):
        s = open(file).read()
        s = s.replace("ABC" ,"EFG")
        f = open(file,'w')
        f.write(s)
        f.close()

我也尝试过这个:

def replace_in_file(file):
    with fileinput.FileInput(file) as file:
        for line in file:
                line.replace("ABC" , "EFG")

但是没有一个不起作用!

我想自动化以下过程:说明

Open file with notepad++
Press ctrl+f
go to replace
and replace "ABC" by "EFG"

最佳答案

我认为在文件中你不能直接替换,所以你也必须写入。否则变更数据将不存在。因此,您还可以创建一个临时文件并在其中写入,或者您可以更改原始文件。所以你的两个函数都是正确的,只需添加类似的东西..

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ): 
    tempFile.write( line.replace( textToSearch, textToReplace ) )

tempFile.close() 

关于python - 文件中的通用字符串替换,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/57168038/

相关文章:

python - 打印字符串中的偶数字符并忽略白色字符串

python - scrapy 的 yield 逻辑被破坏

python - ValueError : Error when checking target: expected dense_108 to have 2 dimensions, 但得到形状为 (36020, 10, 2) 的数组

python - 在运行时更改 django 模型的表名称

元组的 Python 列表,需要解包和清理

python - 使用 Python 将 json 文件从 S3 读取到 sagemaker 笔记本中

python - 将 PyQT/PySide 小部件绑定(bind)到 Python 中的局部变量

python - Pandas group by 和 sum,但在超过一定数量时创建一个新行

c++ - 使用 Visual Studio 2008 构建 boost python 示例

python - 无法加载基于 CI 构建的 Dylib