我有一个输入文件(文件 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()
我确信这可以以一种优雅的方式完成,但是当我尝试上面的代码时,我对阅读和写作有点困惑。输出不符合预期。我的代码有什么问题?
请您参考如下方法:
你可以用一个简单的替换来做到这一点:
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 不起作用(它也可能出现在文件的其他部分),那么您可以使用更具体的模式甚至正则表达式来更准确地替换它.
例如,如果 program 之后,这里我们只替换 ABCDE:
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)
