[Tutor] reading file, adding to each line, writing file
Kent Johnson
kent37 at tds.net
Wed Feb 4 16:42:49 CET 2009
On Wed, Feb 4, 2009 at 10:18 AM, OkaMthembo <zebra05 at gmail.com> wrote:
> 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:
I don't think line will ever be empty, so this test is not needed.
> sentences.insert(len(sentences), line + '-d')
sentences.append(line + '-d') is simpler. Note this appends after the
newline so it is not really what the OP wants.
> file_1.close()
> file_2 = open('pyout', 'w+')
> if len(sentences) > 0:
This test is not needed, if sentences is empty the for statement won't
do anything.
> for sentence in sentences:
> file_2.write(sentence)
The loop could be replaced with
file_2.writelines(sentences)
Kent
More information about the Tutor
mailing list