Как открыть файл, Stud.txt, а затем заменить любые вхождения "А" на "Оранжевый"?
Заменить строку в содержимом файла
Ответ 1
with open("Stud.txt", "rt") as fin:
with open("out.txt", "wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
Ответ 2
Если вы хотите заменить строки в одном и том же файле, вам, вероятно, придется прочитать его содержимое в локальную переменную, закрыть его и снова открыть для записи:
В этом примере я использую оператор 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)
Стоит отметить, что если бы имена файлов были другими, мы могли бы сделать это более элегантно с помощью одного оператора with
.
Ответ 3
#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName, "w") as f:
f.write(newText)
Ответ 4
Что-то вроде
file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
<do stuff with the result>
Ответ 5
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)
Ответ 6
Если вы используете Linux и просто хотите заменить слово " dog
словом " cat
вы можете сделать следующее:
text.txt:
Hi, i am a dog and dog are awesome, i love dogs! dog dog dogs!
Команда Linux:
sed -i 's/dog/cat/g' test.txt
Выход:
Hi, i am a cat and cat are awesome, i love cats! cat cat cats!
Исходное сообщение: https://askubuntu.com/questions/20414/find-and-replace-text-within-a-file-using-commands
Ответ 7
проще всего сделать это с помощью регулярных выражений, считая, что вы хотите перебирать каждую строку в файле (где будет храниться "A" ).
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)