[Python Glasgow] How to write lines that start with TRAN to another output file

Dougal Matthews dougal85 at gmail.com
Thu Mar 21 14:22:27 CET 2013

On Thursday, 21 March 2013 at 13:00, Hedieh Ebrahimi wrote:

> Hi all, 
> 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())
> 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?

I tried your code and it worked fine for me. Here is my output: http://dpaste.com/1030136/

You can see the code, then input file, the output of it running (true printed three times) and then the output file contents.

The only thing I can think of is the file permissions. What output do you see when you run the code?

-------------- next part --------------
An HTML attachment was scrubbed...
URL: <http://mail.python.org/pipermail/glasgow/attachments/20130321/c8dac8a5/attachment.html>

More information about the Glasgow mailing list