[Tutor] reading file, adding to each line, writing file

OkaMthembo zebra05 at gmail.com
Wed Feb 4 16:18:13 CET 2009


The following is adapted from my humble text processing script that i use at
work for a recurring task of mine. Any excuse not to use Java all day :)

There was an error with my other posts. Pardon the triple posting - won't
happen again soon.



    file_1 = open('step2', 'r+')
    lines = file_1.readlines()
    sentences = []
    for line in lines:
        if line:
            sentences.insert(len(sentences), line + '-d')
    file_1.close()
    file_2 = open('pyout', 'w+')
    if len(sentences) > 0:
        for sentence in sentences:
            file_2.write(sentence)
    file_2.close()




On Wed, Feb 4, 2009 at 4:30 PM, David <ldl08 at gmx.net> wrote:

> Hello everybody,
>
> I have easily spent some four hours on this problem, and I am now asking
> for rescue.
>
> Here is what I am trying to do: I have a file ("step2", with some 30 or so
> lines. To each line I would like to add " -d" at the end. Finally, I want to
> save the file under another name ("pyout".
> So far I have managed to read the file, line by line, and save it under
> another name:
>
> <code>
>
> # add " -d" to each line of a textfile
>
> infile = open("step2", 'r') # open file for appending
> outfile = open("pyout","a") # open file for appending
>
> line = infile.readline()    # Invokes readline() method on file
> while line:
>    outfile.write(line),    # trailing ',' omits newline character
>    line = infile.readline()
>
> infile.close()
> outfile.close()
>
> </code>
>
> As I said, before writing to file "pyout" I would like to append the string
> " -d" to each line. But how, where? I can't append to strings (which the
> lines gained with infile.readline() seem be), and my trial and error
> approach has brought me nothing but a headache.
>
> Thanks for your help!
>
> David
>
> _______________________________________________
> Tutor maillist  -  Tutor at python.org
> http://mail.python.org/mailman/listinfo/tutor
>



-- 
Lloyd Dube
-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/tutor/attachments/20090204/b6a2653e/attachment.htm>


More information about the Tutor mailing list