[Tutor] question

Luke Paireepinart rabidpoobear at gmail.com
Wed Feb 14 19:14:01 CET 2007


Alan Gauld wrote:
> "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:
>     clean1.append(i[26:40])
>
> And since you can iterate over a file the whole thing shrinks to:
>
> clean1 = []
> for i in open('arp.txt'):
>     clean1.append(i[26:40])
> print clean1
>
> Or even more succinctly:
>
> clean1 = [i[26:40] for i in open('arp.txt')]
>   
Would this file stay open until the scope changes or is it immediately 
garbage collected, or does something else happen?
Is it unnecessary to use the close methods of files if there are no 
references to the object anymore?
If you had a variable assigned to an open file, and then assigned it to 
something else,
the file would be automatically closed?
Are there any caveats here or is this as safe as closing the file in a 
separate statement?
I've always assumed that you had to explicitly close files.

If you did
file('something.out', 'w').writelines(['testitem1\n','testitem2\n'])
the file would be closed immediately after this was done executing, right?
is there a special func like __init__ that is called when files need to 
be deleted? perhaps __del__?

Feel free to refer me to a tutorial/reference that explains python 
garbage collecting or something.
I would google it myself but I have a huge gigantic test tomorrow.
If no one feels like answering I'll look into it this weekend.
Thanks.



More information about the Tutor mailing list