开发者

Modifying text documents with python

开发者 https://www.devze.com 2023-03-19 15:31 出处:网络
Let\'s say I had a .txt document with 1,000 names in it. The document would look like this: Jon Jane Joe Jack

Let's say I had a .txt document with 1,000 names in it. The document would look like this:

Jon Jane Joe Jack Jeremy

and, so on.

Now, let's say, I wanted to append "is lame." to each of the names. So, I'd want the list to look like t开发者_如何学JAVAhis:

Jon is lame. Jane is lame. Joe is lame. Jack is lame. Jeremy is lame.

and, so on.

How would I do this with python from the command line?


See http://docs.python.org/tutorial/inputoutput.html#reading-and-writing-files.

In a nutshell:

f = open('my_names_file.txt')
data = f.read()
f.close()
output = ""
for name in data.split(' '):       # This assumes each name is separated 
    output += name + " is lame. "  # by a space and no name contains a space
print output

It's just as easy to write the output back into a file. It's explained well in the docs.


print ' '.join(i + ' is lame.' for i in open(fname).read().split())


This isn't exactly python specific, but you get the idea....

In a loop parsing each token (name):
1.  Get the name into a string
2.  Append "is lame" or whatever else to the string
3.  Append that string onto a buffer

After the loop is over, replace your document with the new buffer.


>>> s="Jon Jane Joe Jack Jeremy "
>>> s.replace(" ", " is lame. ")
'Jon is lame. Jane is lame. Joe is lame. Jack is lame. Jeremy is lame. '


Please find below a very basic sample:

outputLines = []
with open('c:\\file.txt', 'r') as f:
    for line in f:
        if line.strip():
            outputLines.append(' is lame. '.join(line.strip().split()))
with open('c:\\file.txt', 'w') as f:
    for line in outputLines:
        f.write(line+'\n')
0

精彩评论

暂无评论...
验证码 换一张
取 消