Shr*_*ram 179 python string replace file python-3.x
如何使用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...' )
Run Code Online (Sandbox Code Playgroud)
输入文件:
嗨,这是abcd,这是abcd
这是虚拟文本文件.
这就是搜索和替换工作方式abcd
当我在上面的输入文件中搜索并替换'abcd'中的'ram'时,它就像魅力一样.但是当我这样做时,反之亦然,即用'ram'代替'abcd',最后会留下一些垃圾字符.
用'ram'代替'abcd'
嗨这是ram嗨这是ram
这是虚拟文本文件.
这就是rambcd的搜索和替换工作方式
Jac*_*ley 277
正如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)
Run Code Online (Sandbox Code Playgroud)
除非你有一个庞大的文件可以使用,它太大而无法一次性加载到内存中.
jfs*_*jfs 210
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='')
Run Code Online (Sandbox Code Playgroud)
小智 48
正如杰克艾德利发布的那样,JF塞巴斯蒂安指出,这段代码不起作用:
# 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)`
Run Code Online (Sandbox Code Playgroud)
但是这段代码会起作用(我已经测试过了):
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()
Run Code Online (Sandbox Code Playgroud)
使用此方法,filein和fileout可以是同一个文件,因为Python 3.3将在打开写入时覆盖该文件.
Jay*_*ram 43
你可以这样做替换
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()
Run Code Online (Sandbox Code Playgroud)
Yuy*_*ina 18
您也可以使用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)
Run Code Online (Sandbox Code Playgroud)
小智 9
以读取模式打开文件。以字符串格式读取文件。按预期替换文本。关闭文件。再次以写入模式打开文件。最后,将替换的文本写入同一文件。
try:
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.")
Run Code Online (Sandbox Code Playgroud)
(pip 安装 python-util)
from pyutil import filereplace
filereplace("somefile.txt","abcd","ram")
Run Code Online (Sandbox Code Playgroud)
将所有出现的“abcd”替换为“ram”。
该函数还通过指定支持正则表达式regex=True
from pyutil import filereplace
filereplace("somefile.txt","\\w+","ram",regex=True)
Run Code Online (Sandbox Code Playgroud)
免责声明:我是作者(https://github.com/MisterL2/python-util)
迟到的答案,但这就是我用来在文本文件中查找和替换的内容:
with open("test.txt") as r:
text = r.read().replace("THIS", "THAT")
with open("test.txt", "w") as w:
w.write(text)
Run Code Online (Sandbox Code Playgroud)
归档时间: |
|
查看次数: |
522392 次 |
最近记录: |