我想循环一个文本文件的内容,并在一些行上进行搜索和替换,并将结果写回文件。我可以先把整个文件加载到内存中,然后再把它写回来,但这可能不是最好的方法。
在下面的代码中,做到这一点的最佳方法是什么?
f = open(file)
for line in f:
if line.contains('foo'):
newline = line.replace('foo', 'bar')
# how to write this newline back to the file
根据托马斯·沃特内达尔的回答。
然而,这并没有准确地回答原始问题的行对行部分。函数仍然可以在行对行的基础上进行替换
此实现替换文件内容而不使用临时文件,因此文件权限保持不变。
此外,re.sub代替replace,允许正则表达式替换而不是纯文本替换。
将文件读取为单个字符串而不是逐行读取允许多行匹配和替换。
import re
def replace(file, pattern, subst):
# Read contents from file as a single string
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
# Use RE package to allow for replacement (also allowing for (multiline) REGEX)
file_string = (re.sub(pattern, subst, file_string))
# Write contents to file.
# Using mode 'w' truncates the file.
file_handle = open(file, 'w')
file_handle.write(file_string)
file_handle.close()
Fileinput非常简单,就像之前的答案中提到的那样:
import fileinput
def replace_in_file(file_path, search_text, new_text):
with fileinput.input(file_path, inplace=True) as file:
for line in file:
new_line = line.replace(search_text, new_text)
print(new_line, end='')
解释:
fileinput可以接受多个文件,但我更喜欢在处理每个文件时立即关闭它。因此,将单个file_path放在with语句中。
当inplace=True时,print语句不打印任何东西,因为STDOUT被转发到原始文件。
End = " in print语句是消除中间空白的新行。
你可以这样使用它:
file_path = '/path/to/my/file'
replace_in_file(file_path, 'old-text', 'new-text')
根据托马斯·沃特内达尔的回答。
然而,这并没有准确地回答原始问题的行对行部分。函数仍然可以在行对行的基础上进行替换
此实现替换文件内容而不使用临时文件,因此文件权限保持不变。
此外,re.sub代替replace,允许正则表达式替换而不是纯文本替换。
将文件读取为单个字符串而不是逐行读取允许多行匹配和替换。
import re
def replace(file, pattern, subst):
# Read contents from file as a single string
file_handle = open(file, 'r')
file_string = file_handle.read()
file_handle.close()
# Use RE package to allow for replacement (also allowing for (multiline) REGEX)
file_string = (re.sub(pattern, subst, file_string))
# Write contents to file.
# Using mode 'w' truncates the file.
file_handle = open(file, 'w')
file_handle.write(file_string)
file_handle.close()
使用hamishmcn的答案作为模板,我能够在文件中搜索与我的正则表达式匹配的一行,并将其替换为空字符串。
import re
fin = open("in.txt", 'r') # in file
fout = open("out.txt", 'w') # out file
for line in fin:
p = re.compile('[-][0-9]*[.][0-9]*[,]|[-][0-9]*[,]') # pattern
newline = p.sub('',line) # replace matching strings with empty string
print newline
fout.write(newline)
fin.close()
fout.close()
下面是另一个经过测试的例子,它将匹配搜索和替换模式:
import fileinput
import sys
def replaceAll(file,searchExp,replaceExp):
for line in fileinput.input(file, inplace=1):
if searchExp in line:
line = line.replace(searchExp,replaceExp)
sys.stdout.write(line)
使用示例:
replaceAll("/fooBar.txt","Hello\sWorld!$","Goodbye\sWorld.")