我有一个输入文件(文件A),如下所示:
Start of the program
This is my first program ABCDE
End of the program
我收到程序名称'PYTHON'
作为输入,我需要用它替换'ABCDE'
。因此,我阅读了文件以找到单词'program'
,然后如下所示替换字符串。我已经在程序中做到了。然后,我想将更新后的字符串写到原始文件中,而不更改第1行或第3行-仅更改第2行。
Start of the program
This is my first program PYTHON
End of the program
我的代码:
fileName1 = open(filePath1, "r")
search = "program"
for line in fileName1:
if search in line:
line = line.split(" ")
update = line[5].replace(line[5], input)
temp = " ".join(line[:5]) + " " + update
fileName1 = open(filePath1, "r+")
fileName1.write(temp)
fileName1.close()
else:
fileName1 = open(filePath1, "w+")
fileName1.write(line)
fileName1.close()
我确信这可以用一种优雅的方式完成,但是当我尝试上述代码时,我对读写产生了一些困惑。输出不符合预期。我的代码有什么问题?
答案 0 :(得分:1)
您可以通过简单的替换操作来完成此操作:
file_a.txt
Start of the program`
This is my first program ABCDE`
End of the program`
代码:
with open('file_a.txt', 'r') as file_handle:
file_content = file_handle.read()
orig_str = 'ABCDE'
rep_str = 'PYTHON'
result = file_content.replace(orig_str, rep_str)
# print(result)
with open('file_a.txt', 'w') as file_handle:
file_handle.write(result)
如果仅替换ABCDE
也行不通(它也可能出现在文件的其他部分),那么您可以使用更具体的模式甚至是正则表达式来更准确地替换它。
例如,在这里,如果ABCDE
之后是program
,则只需替换它即可:
with open('file_a.txt', 'r') as file_handle:
file_content = file_handle.read()
orig_str = 'ABCDE'
rep_str = 'PYTHON'
result = file_content.replace('program {}'.format(orig_str),
'program {}'.format(rep_str))
# print(result)
with open('file_a.txt', 'w') as file_handle:
file_handle.write(result)