[Tutor] Read lines opening with a particular set of characters from a file

Peter Otten __peter__ at web.de
Sat Nov 28 08:40:07 EST 2015


Br. Sayan wrote:

> I am doing the following :
> 
> with open('Manwal.txt') as infile, open('Manwal_req.txt','w') as outfile:
>     for line in infile:
>         if line.startswith(('R')):
>             outfile.write(line)
> 
> It is executing without error but returns a blank file. Where is the
> problem?

Your sample data uses the "\r" character to separate lines. This has gone 
out of fashion, but Python 3 handles it gracefully. 

In Python 2 you have to enable "universal newlines" explicitly with

with open("Manwal.txt", "U") as infile, ...
   ...

This will recognize "\r", "\r\n", and "\n" as line separators, and translate 
all of them to "\n".



More information about the Tutor mailing list