我是一名新的编码员,他在Python 3中接受了一些兼职培训,最近我给了一个家庭作业来编写一个程序,允许用户输入文件的名称,输入他们想要改变的文本。该文件,然后更改它。 我写了一些代码,并正在试验" r +"功能,但我的代码似乎没有工作。我一直试图在我测试的.txt文件中更改的行不会改变 如果有人能给我一些提示,我将非常感激。
# Build main
def main():
# Get file name and open for reading and writing
toalter = input("Please enter a target file: ")
infile = open(toalter, "r+")
# Get input of the line to be changed, and what it is to change to
old = input("Please enter the text you want to change: ")
new = input("Please enter what you want it changed to: ")
for line in infile:
if old in line:
line = line.replace(old, new)
infile.close()
main()
答案 0 :(得分:0)
假设我有一个包含以下内容的test.txt文件。我想用椰子代替Apple。这就是我接近它的方式。
Apple
Orange
Strawberry
Kiwi
>>> def replace (old, new):
... path = '/testfiles/test.txt'
... with open (path) as f:
... file = f.read ()
... if old in file:
... file = file.replace (old, new)
... with open (path, 'w') as f:
... f.write (file)
...
>>>
>>> replace ('Apple', 'Coconut')
<强>输出强>
Coconut
Orange
Strawberry
Kiwi
如果您的文件包含多个Apple实例,那么您需要将逻辑更改为此。
def replace (old, new):
... newstring = ''
... path = '/testfiles/test.txt'
... with open (path) as f:
... for line in f:
... if old in line:
... newstring += line.replace (old, new)
... else:
... newstring += line
... with open (path, 'w') as f:
... f.write (newstring)
...
>>>