Changing a line in a text file
Vishnu
vishnu at acmet.com
Mon Apr 25 05:57:56 EDT 2005
Hi,
Here is the program for replacing 'line2' with 'newline'.
inp_file.txt contains,
line1
line2
line3
line4
EOF
#-- Program starts
#Get the inp file in to a list
inp_file_list = [x for x in open('inp_file.txt')]
#modify the desired line, Note: you should include newline
inp_file_list[1] = 'xxx\n'
#Open the same file
write_to_file = open('inp_file.txt', 'w')
#write the list in to the file
write_to_file.writelines(inp_file_list)
#close the file
write_to_file.close()
#-- Program ends
Hope someone will give better idea.
HTH,
Vishnu
-----Original Message-----
From: python-list-bounces+vishnu=acmet.com at python.org
[mailto:python-list-bounces+vishnu=acmet.com at python.org] On Behalf Of
kah
Sent: Monday, April 25, 2005 3:09 PM
To: python-list at python.org
Subject: Changing a line in a text file
How do I change a line in a file??
For example I have the follwing text in my file:
line1
line2
line3
line4
How do I replace 'line2' with 'newline'. Since the write operation in
python will overwrite everything.
Regards,
Kah
--
http://mail.python.org/mailman/listinfo/python-list
More information about the Python-list
mailing list