[Tutor] loop couldn't work well and file couldn't close

Alan Gauld alan.gauld at btinternet.com
Wed Apr 23 02:28:03 CEST 2014

On 22/04/14 17:13, baidusandy wrote:
> I'm a newbie to Python. I want to make python useful to my work, to
> write a script for get some data out. But there are some setbacks. I
> really needs your help. Please, help me.

Its too late for me to study your code properly but here are
a few immediate observations...

> -------the first one--------------
> for x in range(1,a):
>    tem=open('results\\temp'+str(x))
>    tem.seek(0)

You shouldn'yt need to seek(0) immediately after opening to
read since the file cursor will already be at the beginning.

>    i_line=tem.readline()
>    while i_line:
>      i_list=i_line.split('\t')
>      if float(i_list[1])<float(b[x]):
>        o=open('results\\'+str(x),'a')
>        o.write(i_line)
>        o.close
>      else:
>        tem02=open('results\\temp'+str(x+1),'a')
>        tem02.write(i_line)
>        tem02.close
>      i_line=tem.readline()

This looks like it could be done more elegantly using a
for loop over the file;

for i_line in tem:

>    tem.close

And if you use with you don;t need a close:

with open(...) as tem:
    for i_line in tem:

> for x in range(a,a+1):
>    close('results\\temp'+str(x))

You can't close a file by passing its filename in.
You can only close it by calling close on the open file
object - which you have already done for your files
in the earlier loops. (Or if you use 'with' is done

>    os.rename('results\\temp'+str(x),'results\\'+str(x))

> ## for the last line, the code couldn't work. I run the script in
> Windows XP, i don't know if there is something to do with the OS.

Wjhat do you mean by 'wouldnt work'?
Do you get an error? If the file not changed?
Is it lost? We need more detail.

> --------for another question:-----------
> for x in range (a,a+1):
>    m=open(01)

I assume the lack of quotes is a typo? Its better
to paste real code rather than retype it.

>    m_line=m.readline()
>    b=open('02','w')
>    while m_line:
>      b.write(m_line)
>      m_line=m.readline()

Again this would be better as a for loop

for m_line in m:

But better still would be to just copy the file
using the shutil.copy() function.

>    b.close
>    m.close
> ## for this one, file 02 and 01are not the same. to tell the truth, the
> last line of 01 has not been written into file 02. What's wrong?

Sorry, not sure, it looks OK from that point of view.

Alan G
Author of the Learn to Program web site

More information about the Tutor mailing list