how to modify row content of file in python?

H

holmes86

hi,everyone

Is there function of modify row content in python? just like 'sed' in
shell,thanks
 
L

Lutz Horn

Hi,

* holmes86 [Tue, 27 Oct 2009 00:55:36 -0700]:
Is there function of modify row content in python? just like 'sed' in
shell,thanks

Sed doesn't actually modify the contents of a file. In normal operation
mode it reads from STDIN and writes to STDOUT. Some versions of sed
provide the -i option to

edit files in place (makes backup if extension supplied)

You could program a similar behaviour in Python using the re module.

Lutz
 
G

Gabriel Genellina

* holmes86 [Tue, 27 Oct 2009 00:55:36 -0700]:
Is there function of modify row content in python? just like 'sed' in
shell,thanks

Sed doesn't actually modify the contents of a file. In normal operation
mode it reads from STDIN and writes to STDOUT. Some versions of sed
provide the -i option to

edit files in place (makes backup if extension supplied)

You could program a similar behaviour in Python using the re module.

There is the fileinput module:
http://docs.python.org/library/fileinput.html
 
S

Simon Hibbs

hi,everyone

Is there function of modify row content in python? just like 'sed' in
shell,thanks

You would do something like this, which acepts a CSV file from stdin
and sends the first column to stdout (prints it), which you could
redirect to a file or pipe to another command.

import sys

with infile = sys.stdin.readlines():
for line in infile.readlines():
columns = line.split(',')
print columns[0]


This code is not tested as Windows Explorer just crashed on my box
(effing windows - I'm at work so no Mac. *sob*).

One thing to look out for is that 'columns' is being created each time
through the loop, which works fine. If you modified the code to append
to it instead, you would need to create it before entering the loop as
you can't append to something that doesn't exist.


Simon Hibbs
 

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
473,744
Messages
2,569,479
Members
44,899
Latest member
RodneyMcAu

Latest Threads

Top