用Python替换包含字符串的行

用Python替换包含字符串的行,python,replace,Python,Replace,我试图在文件中搜索包含特定文本的行,然后用新行替换整行 我正在尝试使用: pattern = "Hello" file = open('C:/rtemp/output.txt','w') for line in file: if pattern in line: line = "Hi\n" file.write(line) 我得到一个错误,说: io.UnsupportedOperation: not readable 我不确定我做错了什么,请有人帮

我试图在文件中搜索包含特定文本的行,然后用新行替换整行

我正在尝试使用:

pattern = "Hello"
file = open('C:/rtemp/output.txt','w')

for line in file:
    if pattern in line:
        line = "Hi\n"
        file.write(line)
我得到一个错误,说:

io.UnsupportedOperation: not readable

我不确定我做错了什么,请有人帮忙。

您打开文件时使用了“w”,这意味着您将要写入该文件。然后你试着从中阅读。所以我错了


尝试读取该文件,然后打开另一个文件以写入输出。如果需要,完成后,删除第一个文件并将输出(temp)文件重命名为第一个文件的名称。

您对python一定很陌生^_^

你可以这样写:

pattern = "Hello"
file = open(r'C:\rtemp\output.txt','r')  # open file handle for read
# use r'', you don't need to replace '\' with '/'
# open file handle for write, should give a different file name from previous one
result = open(r'C:\rtemp\output2.txt', 'w')  

for line in file:
    line = line.strip('\r\n')  # it's always a good behave to strip what you read from files
    if pattern in line:
        line = "Hi"  # if match, replace line
    result.write(line + '\n')  # write every line

file.close()  # don't forget to close file handle
result.close()

或者,您打开文件只是为了写入。要做到这两个,你需要这样做:谢谢,这就解决了问题