readline() - problem

Wesley Brooks wesbrooks at gmail.com
Tue Oct 2 07:49:38 EDT 2007


Given a file:

#### t.txt  ####
1 2
1 1
3 1
### end of file ###

file = open('t.txt', 'r')
for i, line in enumerate(file):
    print "Line:", i, "Text:", line

would give the result:

Line: 0 Text: 1 2
Line: 1 Text: 1 1
Line: 2 Text: 3 1

To check the third character in each line:

for line in file:
    if (line != '') and (len(line) > 2):
         if line[2] == '1':
             print "Got line:", line

Would give:

Got line: 1 1
Got line: 3 1

Cheers,

Wesley Brooks

On 02/10/2007, piotr at kolodziejczyk.waw.pl <piotr at kolodziejczyk.waw.pl> wrote:
> Hi!
> I'm a new user of python, and have problem.
> I have a plain ascii file:
> 1aaaaaaaaaaaa1......1
> 1cccccccccccc2......1
> 1xxxxxxxxxxxx1......1
> I want to create a new file which contains only lines with '1' on 15th
> position.
> I've tried this:
>
> import string
> f=open('/test/test.asc','r')
> o=open('/test/out.asc','w')
> for line in f:
>     s= f.readline()
>     if s[15]=='1' :
>        o.write(s)
> o.close()
> f.close()
>
> Why it doesn't work ('s' contains ' ' )?
>
> piotr
>
> --
> http://mail.python.org/mailman/listinfo/python-list
>



More information about the Python-list mailing list