[Tutor] loop couldn't work well and file couldn't close
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):
You shouldn'yt need to seek(0) immediately after opening to
read since the file cursor will already be at the beginning.
> while i_line:
> if float(i_list)<float(b[x]):
This looks like it could be done more elegantly using a
for loop over the file;
for i_line in tem:
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):
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
> ## 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):
I assume the lack of quotes is a typo? Its better
to paste real code rather than retype it.
> while m_line:
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.
> ## 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.
Author of the Learn to Program web site
More information about the Tutor