Gar*_*son 170
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
Run Code Online (Sandbox Code Playgroud)
Ada*_*tan 71
如果您想要替换同一文件中的字符串,您可能必须将其内容读入本地变量,关闭它并重新打开它以进行写入:
我在这个例子中使用了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:
s = f.read()
print('Changing "{old_string}" to "{new_string}" in {filename}'.format(**locals()))
s = s.replace(old_string, new_string)
f.write(s)
Run Code Online (Sandbox Code Playgroud)
值得一提的是,如果文件名不同,我们可以通过单个with语句更优雅地完成此操作.
Mar*_*ahn 37
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
Run Code Online (Sandbox Code Playgroud)
就像是
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
Run Code Online (Sandbox Code Playgroud)
使用 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'))
Run Code Online (Sandbox Code Playgroud)
如果输入和输出文件不同,您可以为read_text和使用两个不同的变量write_text。
如果您想要一个比单个替换更复杂的更改,您可以将 的结果分配read_text给一个变量,对其进行处理并将新内容保存到另一个变量中,然后使用write_text.
如果您的文件很大,您会更喜欢一种不读取内存中整个文件的方法,而是逐行处理它,如 Gareth Davidson 在另一个答案中所示(/sf/answers/288973471/) ,这当然需要使用两个不同的文件进行输入和输出。
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)
Run Code Online (Sandbox Code Playgroud)
如果您使用的是Linux,并且只想替换单词dog,则cat可以执行以下操作:
text.txt:
Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Run Code Online (Sandbox Code Playgroud)
Linux命令:
sed -i 's/dog/cat/g' test.txt
Run Code Online (Sandbox Code Playgroud)
输出:
Hi, i am a cat and cat's are awesome, i love cats! cat cat cats!
Run Code Online (Sandbox Code Playgroud)
原始帖子:https : //askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
| 归档时间: |
|
| 查看次数: |
177006 次 |
| 最近记录: |