-3

I'm trying to search through a file for a line that contain certain text and then replace that entire line with a new line.

I'm trying to use:

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

for line in file:
    if pattern in line:
        line = "Hi\n"
        file.write(line)

I get an error saying:

io.UnsupportedOperation: not readable

I'm not sure what I'm doing wrong, please can someone assist.

ChrisG29
  • 1,501
  • 3
  • 25
  • 45
  • 1
    http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python or this http://stackoverflow.com/questions/17140886/how-to-search-and-replace-text-in-a-file-using-python – MooingRawr Sep 12 '16 at 14:16
  • 4
    You are opening the file for writing only. To do both, you need to do this: http://stackoverflow.com/questions/6648493/open-file-for-both-reading-and-writing – Andy Sep 12 '16 at 14:17

2 Answers2

2

You opened the file with 'w', meaning you are going to write to it. Then you try to read from it. So error.

Try reading from that file, and open another file for writing your output. If needed, when done, delete the first file and rename your output (temp) file to the first file's name.

MMN
  • 576
  • 5
  • 7
-1

You must be very new for python ^_^

You can write it like this:

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()
Belter
  • 3,573
  • 5
  • 42
  • 58