用Python替换包含字符串的行

时间:2016-09-12 14:15:33

标签: 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

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

2 个答案:

答案 0 :(得分:2)

您用' w'打开了文件,这意味着您要写信给它。然后你试着从中读取。所以错误。

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

答案 1 :(得分:-1)

你必须是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()