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

Python 如何搜索和替换文件中的文本?,python,python-3.x,string,file,replace,Python,Python 3.x,String,File,Replace,如何使用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:") fi

如何使用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...' )
输入文件:

您好,这是abcd您好,这是abcd
这是一个虚拟文本文件。
这就是搜索和替换的工作原理
当我在上面的输入文件中搜索“ram”并将其替换为“abcd”时,它就像一个符咒。但当我这样做时,反之亦然,即用“ram”替换“abcd”,一些垃圾字符会留在末尾

将“abcd”替换为“ram”

hi这是ram hi这是ram
这是一个虚拟文本文件。
这就是搜索和替换的工作原理

您可以这样进行更换

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
for line in f1:
    f2.write(line.replace('old_text', 'new_text'))
f1.close()
f2.close()

您的问题源于对同一文件的读写。不要打开
fileToSearch
进行写入,而是打开一个实际的临时文件,然后在完成并关闭
tempFile
后,使用
os。重命名
将新文件移到
fileToSearch

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

除非您要处理的文件太大,无法一次性加载到内存中,或者您担心在向文件写入数据的第二步过程中,如果该过程中断,可能会导致数据丢失。

我的变体,在整个文件上一次加载一个字

我把它读入记忆

def replace_word(infile,old_word,new_word):
    if not os.path.isfile(infile):
        print ("Error on replace_word, not a regular file: "+infile)
        sys.exit(1)

    f1=open(infile,'r').read()
    f2=open(infile,'w')
    m=f1.replace(old_word,new_word)
    f2.write(m)
已支持就地编辑。在这种情况下,它将标准输出重定向到文件:

#!/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='')

正如杰克·艾德利(Jack Aidley)和J.F.塞巴斯蒂安(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)`
但是这段代码可以工作(我已经测试过了):

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

我已经完成了以下操作:

#!/usr/bin/env python3

import fileinput
import os

Dir = input ("Source directory: ")
os.chdir(Dir)

Filelist = os.listdir()
print('File list: ',Filelist)

NomeFile = input ("Insert file name: ")

CarOr = input ("Text to search: ")

CarNew = input ("New text: ")

with fileinput.FileInput(NomeFile, inplace=True, backup='.bak') as file:
    for line in file:
        print(line.replace(CarOr, CarNew), end='')

file.close ()

我稍微修改了Jayram Singh的帖子,以替换每一个“!”的实例字符设置为我希望随每个实例递增的数字。我认为这可能对那些想要修改每行出现多次的字符并想要迭代的人有所帮助。希望这能帮助别人。PS-我对编码非常陌生,所以如果我的帖子在任何方面都不合适,我深表歉意,但这对我来说很有效

f1 = open('file1.txt', 'r')
f2 = open('file2.txt', 'w')
n = 1  

# if word=='!'replace w/ [n] & increment n; else append same word to     
# file2

for line in f1:
    for word in line:
        if word == '!':
            f2.write(word.replace('!', f'[{n}]'))
            n += 1
        else:
            f2.write(word)
f1.close()
f2.close()

您还可以使用
pathlib

from pathlib2 import Path
path = Path(file_to_search)
text = path.read_text()
text = text.replace(text_to_search, replacement_text)
path.write_text(text)

使用单个With块,您可以搜索和替换文本:

with open('file.txt','r+') as f:
    filedata = f.read()
    filedata = filedata.replace('abc','xyz')
    f.truncate(0)
    f.write(filedata)
(pip安装python util)

从pyutil导入文件替换
filereplace(“somefile.txt”、“abcd”、“ram”)
将所有出现的“abcd”替换为“ram”。
该函数还通过指定
regex=True

从pyutil导入文件替换
filereplace(“somefile.txt”,“\\w+,“ram”,regex=True)
免责声明:我是作者()

就像这样:

def find_and_replace(file, word, replacement):
  with open(file, 'r+') as f:
    text = f.read()
    f.write(text.replace(word, replacement))

延迟回答,但这是我用来在文本文件中查找和替换的内容:

with open("test.txt") as r:
  text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
  w.write(text)

除了前面提到的答案之外,下面解释一下为什么在结尾处有一些随机字符:
您是在
r+
模式下打开文件,而不是在
w
模式下打开文件。关键区别在于,
w
模式会在您打开文件时立即清除其内容,而
r+
则不会 这意味着,如果您的文件内容是“123456789”,并且您在其中写入了“www”,那么您将得到“ww456789”。它用新输入覆盖字符,但保留所有剩余输入不变。
您可以使用
truncate()
清除文件内容的一部分,但最好先将更新后的文件内容保存到字符串中,然后执行
truncate(0)
并一次写入所有内容。

或者你可以:D

我已经把这个作为一门课程的练习:打开文件,查找并替换字符串,然后写入一个新文件

class Letter:

    def __init__(self):

        with open("./Input/Names/invited_names.txt", "r") as file:
            # read the list of names
            list_names = [line.rstrip() for line in file]
            with open("./Input/Letters/starting_letter.docx", "r") as f:
                # read letter
                file_source = f.read()
            for name in list_names:
                with open(f"./Output/ReadyToSend/LetterTo{name}.docx", "w") as f:
                    # replace [name] with name of the list in the file
                    replace_string = file_source.replace('[name]', name)
                    # write to a new file
                    f.write(replace_string)


brief = Letter()

我也有同样的问题。问题是,当您在变量中加载.txt时,它就像字符串数组一样使用,而它是字符数组

swapString = []
with open(filepath) as f: 
    s = f.read()
for each in s:
    swapString.append(str(each).replace('this','that'))
s = swapString
print(s)


我尝试了这个方法,用readlines代替read

with open('dummy.txt','r') as file:
    list = file.readlines()
print(f'before removal {list}')
for i in list[:]:
        list.remove(i)

print(f'After removal {list}')
with open('dummy.txt','w+') as f:
    for i in list:
        f.write(i)

这个答案对我有用。以读取模式打开文件。以字符串格式读取文件。按预期替换文本。关闭文件。再次以写入模式打开文件。最后,将替换的文本写入同一文件

    with open("file_name", "r+") as text_file:
        texts = text_file.read()
        texts = texts.replace("to_replace", "replace_string")
    with open(file_name, "w") as text_file:
        text_file.write(texts)
except FileNotFoundError as f:
    print("Could not find the file you are trying to read.")

当你说“最后还剩下一些垃圾字符”时,你能说得更具体一点吗?你看到了什么?用我得到的输出更新了问题。下面是一个很好的答案,实现了
map
,而不是循环:,这就是我所做的,仅供参考(请随意编辑答案):根本原因是无法适当缩短文件的中间部分。也就是说,如果搜索5个字符并替换为3,则将替换搜索的5个字符中的前3个字符;但是另外两个不能被移除,它们只会留在那里。临时文件解决方案通过删除这些“剩余”字符而不是将其写入临时文件来删除这些字符。
with file=open(..):
不是有效的Python(
=
),尽管其意图是明确的
.replace()
不会修改字符串(它是不可变的),因此需要使用返回的值。无论如何,支持大文件的代码,除非你需要搜索和替换跨多行的文本。你说得很对,这就是为什么你应该先测试代码,然后再让自己在互联网上尴尬;)@乔纳斯坦:不,不应该。
with
语句会自动关闭语句块末尾的文件。@JackAidley这很有趣。谢谢你的解释。@JackAidley因为它简短、简单、易于使用和理解,并且解决了很多人都遇到的一个实际问题(因此很多人都在搜索-从而找到你的答案)。
end='
参数应该做什么?
line
swapString = []
with open(filepath) as f: 
    s = f.read()
for each in s:
    swapString.append(str(each).replace('this','that'))
s = swapString
print(s)

with open('dummy.txt','r') as file:
    list = file.readlines()
print(f'before removal {list}')
for i in list[:]:
        list.remove(i)

print(f'After removal {list}')
with open('dummy.txt','w+') as f:
    for i in list:
        f.write(i)
    with open("file_name", "r+") as text_file:
        texts = text_file.read()
        texts = texts.replace("to_replace", "replace_string")
    with open(file_name, "w") as text_file:
        text_file.write(texts)
except FileNotFoundError as f:
    print("Could not find the file you are trying to read.")