如何打开文件Stud.txt,然后用"Orange"替换任何出现的"A"?
请(一如既往)遵循一般问题指南,说明任何特殊限制,显示您迄今为止尝试过的内容,并询问具体让您感到困惑的内容。
另外,请用[homework]标签标记你的作业。
相关:如何使用Python搜索和替换文件中的文本?
1
2
3
4with open("Stud.txt","rt") as fin:
with open("out.txt","wt") as fout:
for line in fin:
fout.write(line.replace('A', 'Orange'))
文本模式的"t"仅为Python 3。此外,您为输出文件提供了上下文管理器,但无法关闭输入文件,这似乎不一致。
@katrielalex:没有downvotes,我根本没有upvote。但是,给出家庭作业的答案并不是正确的方法
@Blue:啊,对不起。
呃,并没有注意到这被标记为"家庭作业"。我不会删除我的答案,但将来会更加小心
我不需要这个作业,它帮助我极大地....
"给出家庭作业问题的答案"是一个非常愚蠢的评论。如果有人想要帮助,那就帮助他们。不是每个人都想要做他们的硬件,有些人真的想学点东西......
但是你这样重命名文件,更糟糕的是,你正在创建一个新文件
@nakkini删除旧文件并重命名新文件是执行此类操作的标准方法,没有操作系统支持文本文件作为可编辑行的流。有趣的是,你会想到这一点。
我确实需要这个作业,这对我帮助很大
如何在同一个文件中执行此操作?
@shurrok看到这个答案:stackoverflow.com/a/35130508/146642
如果您想要替换同一文件中的字符串,您可能必须将其内容读入本地变量,关闭它并重新打开它以进行写入:
我在这个例子中使用了with语句,它在with块终止后关闭文件 - 通常是在最后一个命令完成执行时,或者是异常。
1
2
3
4
5
6
7
8
9
10
11
12
13
14def 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语句更优雅地完成此操作。
此解决方案更好,因为您不重命名文件,这与上面的答案不同。
为什么在close()之前立即冲洗()?我希望close()会做任何必要的冲洗。
@ChrisPhoenix正确,我们可以使用with并删除close和flush。
1
2
3
4
5
6
7#!/usr/bin/python
with open(FileName) as f:
newText=f.read().replace('A', 'Orange')
with open(FileName,"w") as f:
f.write(newText)
简短,最好的答案IMO
就像是
1
2
3
4
5file = open('Stud.txt')
contents = file.read()
replaced_contents = contents.replace('A', 'Orange')
OP暗示"任何事件发生"这意味着,即使它是一个子串 - 这对你的例子不起作用。
如果您使用的是Linux,只想将dog替换为cat,则可以执行以下操作:
的text.txt:
1Hi, i am a dog and dog's are awesome, i love dogs! dog dog dogs!
Linux命令:
1sed -i 's/dog/cat/g' test.txt
输出:
1Hi, 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
1
2
3
4
5
6
7with 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)
最简单的方法是使用正则表达式,假设你想迭代文件中的每一行(你将存储'A')你做...
1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18import 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)