首页
学习
活动
专区
工具
TVP
发布
社区首页 >问答首页 >如何搜索和替换文件中的文本?

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

Stack Overflow用户
提问于 2013-06-17 13:24:37
回答 20查看 762K关注 0票数 277

如何使用Python 3搜索和替换文件中的文本?

下面是我的代码:

import os
import sys
import fileinput

print ("Text to search for:")
textToSearch = input( "> " )

print ("Text to replace it with:")
textToReplace = input( "> " )

print ("File to perform Search-Replace on:")
fileToSearch  = input( "> " )
#fileToSearch = 'D:\dummy1.txt'

tempFile = open( fileToSearch, 'r+' )

for line in fileinput.input( fileToSearch ):
    if textToSearch in line :
        print('Match Found')
    else:
        print('Match Not Found!!')
    tempFile.write( line.replace( textToSearch, textToReplace ) )
tempFile.close()


input( '\n\n Press Enter to exit...' )

输入文件:

hi this is abcd hi this is abcd
This is dummy text file.
This is how search and replace works abcd

当我在上面的输入文件中搜索并将'ram‘替换为'abcd’时,它的效果很不错。但当我反之亦然,即用'ram‘替换'abcd’时,一些垃圾字符会留在末尾。

将'abcd‘替换为'ram’

hi this is ram hi this is ram
This is dummy text file.
This is how search and replace works rambcd
EN

回答 20

Stack Overflow用户

回答已采纳

发布于 2013-12-15 18:47:01

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='')
票数 311
EN

Stack Overflow用户

发布于 2013-06-17 14:29:51

正如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)

除非你有一个大文件要处理,它太大而不能一次性加载到内存中,或者你担心如果在向文件写入数据的第二步过程中中断,可能会丢失数据。

票数 437
EN

Stack Overflow用户

发布于 2014-04-05 13:19:15

正如Jack Aidley和J.F. Sebastian所指出的那样,这段代码将无法工作:

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

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

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

但是这段代码可以工作(我已经测试过了):

f = open(filein,'r')
filedata = f.read()
f.close()

newdata = filedata.replace("old data","new data")

f = open(fileout,'w')
f.write(newdata)
f.close()

使用这种方法,filein和fileout可以是同一个文件,因为Python 3.3将在打开以进行写入时覆盖该文件。

票数 60
EN
页面原文内容由Stack Overflow提供。腾讯云小微IT领域专用引擎提供翻译支持
原文链接:

https://stackoverflow.com/questions/17140886

复制
相关文章

相似问题

领券
问题归档专栏文章快讯文章归档关键词归档开发者手册归档开发者手册 Section 归档