我怎样才能打开一个名为 Stud.txt 的文件,并将其中的所有出现的 "A" 替换成 "橙色" 呢?
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
如果您想在同一文件中替换字符串,则可能需要将其内容读入一个本地变量,关闭它,然后重新打开以进行写入:
在此示例中,我使用with语句,该语句在with
块终止时关闭文件,无论是在最后一个命令完成执行时还是通过异常。
def inplace_change(filename, old_string, new_string):
# Safely read the input filename using 'with'
with open(filename) as f:
s = f.read()
if old_string not in s:
print('"{old_string}" not found in {filename}.'.format(**locals()))
return
# Safely write the changed content, if found in the file
with open(filename, 'w') as f:
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
值得一提的是,如果文件名不同,我们可以使用单个with
语句更加优雅地完成这项任务。#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
使用pathlib (https://docs.python.org/3/library/pathlib.html)
from pathlib import Path
file = Path('Stud.txt')
file.write_text(file.read_text().replace('A', 'Orange'))
如果输入和输出文件不同,您需要为read_text
和write_text
使用两个不同的变量。read_text
的结果分配给一个变量,对其进行处理并将新内容保存到另一个变量中,然后再使用write_text
保存新内容。类似于什么
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
with open('Stud.txt','r') as f:
newlines = []
for line in f.readlines():
newlines.append(line.replace('A', 'Orange'))
with open('Stud.txt', 'w') as f:
for line in newlines:
f.write(line)
dog
替换为 cat
,则可以执行以下操作:
text.txt:
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux命令:
sed -i 's/dog/cat/g' test.txt
输出:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
原始帖子:https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
在Linux中,您可以使用sed命令来在文件中查找和替换文本。下面是一个示例:
sed -i 's/旧文本/新文本/g' 文件名
这将在指定的文件中查找所有出现的“旧文本”并将其替换为“新文本”。请注意,“g”选项表示全局替换,如果省略该选项,则只会替换每行中第一个匹配项。
import re
input = file('C:\full_path\Stud.txt', 'r')
#when you try and write to a file with write permissions, it clears the file and writes only #what you tell it to the file. So we have to save the file first.
saved_input
for eachLine in input:
saved_input.append(eachLine)
#now we change entries with 'A' to 'Orange'
for i in range(0, len(old):
search = re.sub('A', 'Orange', saved_input[i])
if search is not None:
saved_input[i] = search
#now we open the file in write mode (clearing it) and writing saved_input back to it
input = file('C:\full_path\Stud.txt', 'w')
for each in saved_input:
input.write(each)