replace a line in a text file

L

Luis Solís

I need open a text file, for example

1
2.3 4.5
4.5

open file mode=x
read the file line by line
if some in line i == xx:
replace line i by newline
close file

Thanks in advance
 
P

Peter Hansen

Luis said:
I need open a text file, for example

1
2.3 4.5
4.5

open file mode=x
read the file line by line
if some in line i == xx:
replace line i by newline
close file

A simple approach is

(1) open the file and read all lines from it with readlines(),
then close it.

(2) open the file again in write mode (thus removing the
original), then iterate over the list returned from
readlines() doing your search/replace routine and
writing out the lines as you go using .write(), then
close the file.

If you need more help, I suggest posting some sample code to
show that you have made an effort to write something, or
people might suspect this is a homework assignment that you
are supposed to be figuring out for yourself...

-Peter
 
L

Larry Bates

Assumptions:

1) You wish to replace the first line that matches
(if you want to replace all, remove the ,1 in the
contents.split() function call).

2) File isn't tremendously big, if it is you should
use loop and xreadlines() to process one line at a
time.

3) There are newline characters at the end of each
of these lines (that way I can just throw away the
contents of the line and the newline character will
still be there).

Use the split function to your advantage.

linetoreplace="2.3 4.5"
f=file(filepath)
contents=f.read()
f.close()
contents="".join(contents.split(linetoreplace), 1)
f=file(filepath,'w')
f.write(contents)
f.close()

Larry Bates
Syscon, Inc.
 
S

Sergey Krushinsky

Larry said:
2) File isn't tremendously big, if it is you should
use loop and xreadlines() to process one line at a
time.
Would you suggest using regular expressions in case of a large file? The
first idea which came to my mind when I saw the Luis's question was:

import sys
import re

_FILENAME='test-1.txt'

p = re.compile('^(.*?4\.5.*?)$', re.MULTILINE)
f = open(_FILENAME, 'r')
old_txt = f.read()
f.close()
new_txt = p.sub('', old_txt)
open(_FILENAME, 'w').write(new_txt)

With best regards,
Sergey
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

Forum statistics

Threads
474,280
Messages
2,571,395
Members
48,096
Latest member
charlessmith

Latest Threads

Top