0

I have a text file with the following lines

test1
test2
test3

and I want the python script to insert a new line in the top of the file then edit each line after that like the following

Python
Test : test1 -t
Test : test2 -t
Test : test3 -t

Any suggestions ?

Thanks

abualameer94
  • 91
  • 3
  • 13
  • 1
    Can you post what you have tried? Try to look at the [doc](http://docs.python.org/2/tutorial/inputoutput.html#reading-and-writing-files) – fredtantini Mar 25 '14 at 11:51
  • I don't know the code to insert a new line in the top or how to insert in the beginning for each line or the ending .. I just know how to write in a file – abualameer94 Mar 25 '14 at 11:54
  • 1
    Read the file, make your changes and simply write to a new file or overwrite your old one. You can use `readlines()` to get all lines of a file. – mattmilten Mar 25 '14 at 11:59
  • Check [this answer](http://stackoverflow.com/questions/125703/how-do-i-modify-a-text-file-in-python#125759) and the next one. – fredtantini Mar 25 '14 at 12:00
  • http://stackoverflow.com/questions/5914627/append-line-to-beginning-of-a-file in combination with http://stackoverflow.com/questions/4706499/how-do-you-append-to-file-in-python – Torxed Mar 25 '14 at 12:01

1 Answers1

1

I would stay away from trying to manipulate the file directly - I am even not sure if this is working. It is much simpler to read in the file and then overwrite the new file - as long as your input file will never exceed your memory:

with open('file.txt') as fin:
    # get lines of the file as list
    lines = fin.readlines()
# Overwrite file.txt with new content
with open('file.txt','w') as fout:
    fout.write('Python\n')
    for line in lines:
        fout.write('Test: ' + line.strip() + ' -t\n')

If memory is of concern and you don't mind to get a new file:

with open('file.txt') as fin:
    fout = open('newfile.txt','w')
    fout.write('Python\n')
    for line in fin:
        fout.write('Test: ' + line.strip() + ' -t\n')
    fout.close()
oekopez
  • 1,080
  • 1
  • 11
  • 19