[Tutor] question

Alan Gauld alan.gauld at btinternet.com
Sat Nov 4 01:31:16 CET 2006

"Doug Potter" <dpotter at nc.rr.com> wrote
>I don't get  the output I would expect from the following.

> >>> a = open('arp.txt')
> >>> file = a.read()
> >>> file = file.split('\n')

Easier to do

file = open('arp.txt').readlines()

But file is a bad name since its an alias for open...

> >>> b = open('arplist.txt','w')

Not sure why you do this

> >>> clean1 = []
> >>>

clean is an empty list

> >>> for i in file:
> ...         clean1 = i[26:40]

clean is now overwritten by a string until you reach the 
end of the file upon which clean1 will be an empty string

> >>> clean1
> ''

Which it is...

I think you may have meant to use the append method

for i in file:

And since you can iterate over a file the whole thing shrinks to:

clean1 = []
for i in open('arp.txt'):
print clean1

Or even more succinctly:

clean1 = [i[26:40] for i in open('arp.txt')]
print clean1


Alan Gauld
Author of the Learn to Program web site

More information about the Tutor mailing list