4

Possible Duplicate:
Search and replace a line in a file in Python
How do I modify a text file in Python?

I have an input file that I need to rewrite with the different files needed to be modified before running a program. I have tried a variety of the solutions on here but none of them seem to work. I end up just overwriting my file with a blank file

f = open(filename, 'r+')
text = f.read()
text = re.sub('foobar', 'bar', text)
f.seek(0)
f.write(text)
f.truncate()
f.close()

Or with that code for instance the name I am changing is different each time I run the program so I need to replace the entire line not just one keyword

Community
  • 1
  • 1
matkapl
  • 43
  • 1
  • 1
  • 4
  • See if the answer for [Search and replace a line in a file in Python](http://stackoverflow.com/questions/39086/search-and-replace-a-line-in-a-file-in-python?rq=1) might work for you. – cbare Dec 10 '12 at 20:12

2 Answers2

3

A simple way may be to read the text into a string, then concatenate the string with the text you want to write:

infile = open('hey.txt','r+')
content = infile.read()
text = ['foo','bar']
for item in text:
     content +=item  #adds 'foo' on first iteration, 'bar' on second
infile.write(content)
infile.close()

or to change a particular key word:

infile = open('hey.txt','r+')
content = infile.read()
table = str.maketrans('foo','bar')
content = content.translate(table)  #replaces 'foo' with 'bar'
infile.write(content)
infile.close()

or to change by line, you can use readlines and refer to each line as the index of a list:

infile = open('hey.txt','r+')
content = infile.readlines() #reads line by line and out puts a list of each line
content[1] = 'This is a new line\n' #replaces content of the 2nd line (index 1)
infile.write(content)
infile.close()

Maybe not a particularly elegant way to solve the problem, but it could be wrapped up in a function and the 'text' variable could be a number of data types like a dictionary, list, etc. There are also a number of ways to replace each line in a file, it just depends on what the criteria are for changing the line (are you searching for a character or word in the line? Are you just looking to replace a line based on where it is in the file?)--so those are also some things to consider.

Edit: Added quotes to third code sample

starryknight64
  • 504
  • 7
  • 15
Sandwich Heat
  • 559
  • 1
  • 8
  • 20
  • `.translate(table)` will replace `f` with `b` and `o` with `r`... definitely different behaviour than stated and from `str.replace`... – Jon Clements Dec 10 '12 at 20:21
  • It's worth using the `with` statement to open files - it has many advantages and no downsides. – Gareth Latty Dec 10 '12 at 20:22
  • Jon, you are right, sorry about that. Do NOT use the translate method! – Sandwich Heat Dec 10 '12 at 20:29
  • I think your last one should work! Thanks – matkapl Dec 11 '12 at 00:43
  • When I run that I receive `infile.write(content) TypeError: expected a character buffer object` – matkapl Dec 11 '12 at 01:25
  • Though ugly this solution ends up working infile = open('file.txt', 'r+') content = infile.readlines() #reads line by line and out puts a list of each line content[1] = "foo \n" #replaces content of the 2nd line (index 1) infile.close infile = open('file.txt', 'w') #clears content of file. infile.close infile = open('file.txt', 'r+') for item in content: #rewrites file content from list infile.write("%s" % item) infile.close() Thank you everyone for your help!! I'll post this as an answer as soon as stackoverflow lets me.... – matkapl Dec 11 '12 at 01:52
  • Make sure that you use: ```infile.seek(0)``` if trying to replace ```content[0]```, (the top line) or any other line potentially "above" the one you are modifying...Otherwise you will get the error ```IndexError: list assignment index out of range``` and if not using '''try''' blocks this will crash your script! (tested with Python 2.7) '''infile.tell()''' will return your index too btw. – eulerworks May 26 '17 at 18:05
0

Though ugly this solution ends up working

infile = open('file.txt', 'r+')
content = infile.readlines() #reads line by line and out puts a list of each line
content[1] = "foo \n" #replaces content of the 2nd line (index 1)
infile.close
infile = open('file.txt', 'w') #clears content of file. 
infile.close
infile = open('file.txt', 'r+')
for item in content: #rewrites file content from list 
    infile.write("%s" % item)
infile.close()

Thanks for all the help!!

matkapl
  • 43
  • 1
  • 1
  • 4