[Python Glasgow] How to write lines that start with TRAN to another output file
Kevin McDermott
kevin.mcdermott at gmail.com
Thu Mar 21 14:13:37 CET 2013
Hello
> I am trying to write the below code to be able to read from a text
> file and fine lines that start with
> TRAN and then write this line and the next 2 following lines to
> another file called Output.txt.
>
> my code is as below:
>
>
> with open('p.txt') as f1:
> with open('Output.txt', 'a') as f2:
> for line in f1:
> if line.startswith('TRAN'):
> print("true")
> f2.write(line)
> f2.write(f1.next())
> f2.write(f1.next())
>
Assuming that your code is indented correctly...this looks ok.
> but when i type python he.py in folder where the p.txt and Output.txt
> are located, nothing happens and no data is written to the output file.
>
> Could somebody please tell me where is my error?
Testing it against a file that looks like this...
TRAN
line1
line2
TRAN
line3
line4
NOTHING
NOTHING
NOTHING
TRAN
line5
line6
Works fine.
Kevin
More information about the Glasgow
mailing list