您好, 欢迎来到 !    登录 | 注册 | | 设为首页 | 收藏本站

Python-如何搜索和替换文件中的文本?

Python-如何搜索和替换文件中的文本?

fileinput已经支持就地编辑。stdout在这种情况下,它将重定向文件

#!/usr/bin/env python3
import fileinput

with fileinput.FileInput(filename, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(text_to_search, replacement_text), end='')

正如michaelb958指出的那样,您不能用其他长度的数据替换在原处,因为这会使其余部分无法正确放置。我不同意其他海报,建议您从一个文件中读取并写入另一个文件。相反,我将文件读入内存,修复数据,然后在单独的步骤中将其写出到同一文件中。

# Read in the file
with open('file.txt', 'r') as file :
  filedata = file.read()

# Replace the target string
filedata = filedata.replace('ram', 'abcd')

# Write the file out again
with open('file.txt', 'w') as file:
  file.write(filedata)

除非您要处理的海量文件太大而无法一次加载到内存中,否则您担心如果在将数据写入文件的第二步期间该过程被中断,则可能会丢失数据。

python 2022/1/1 18:24:16 有171人围观

撰写回答


你尚未登录,登录后可以

和开发者交流问题的细节

关注并接收问题和回答的更新提醒

参与内容的编辑和改进,让解决方法与时俱进

请先登录

推荐问题


联系我
置顶