Can not find a file in CMD model python when everything is OK in IDLE

  • Thread starter Sullivan WxPyQtKinter
  • Start date
S

Sullivan WxPyQtKinter

I use python on Windows XP platform. I find that if I write a .py file
in a directory, such as windows desktop, in which a file named
'ticket.txt' is located:

f=open("ticket.txt")
print f.read()


In IDLE, this py file work all right. But if I launch python
interpretor in the command shell like this:


C:\Documents and Settings\Xiaozhong Zheng>python "C:\Documents and
Settings\Xiaozhong Zheng\Desktop\t.py"


The interpretor would not find the file.


Traceback (most recent call last):
File "C:\Documents and Settings\Xiaozhong Zheng\Desktop\t.py", line
1, in ?
f=open("ticket.txt")
IOError: [Errno 2] No such file or directory: 'ticket.txt'


Anyone knows why?


In addition, if I start IIS web service that runs .py file as CGI
program, then this .py file also works.
 
F

Fredrik Lundh

Sullivan WxPyQtKinter said:
In IDLE, this py file work all right. But if I launch python
interpretor in the command shell like this:


C:\Documents and Settings\Xiaozhong Zheng>python "C:\Documents and
Settings\Xiaozhong Zheng\Desktop\t.py"

The interpretor would not find the file.

open("ticket.txt") means "look for ticket.txt in the current directory",
not in the directory where the PY file lives. if you change to the Desk-
top directory before you run the Python interpreter, your script should
work as expected.

to fix this, you can

- use a full path

or

- use os.path.basedir(__file__) to get the directory where the module
lives, and do something like

root = os.path.basedir(__file__)
ticketfile = os.path.join(root, "ticket.txt")
f = open(ticketfile)

</F>
 
S

Sullivan WxPyQtKinter

I see. I once was a VB programmer. In VB, the current directory is
always set to where the module locates before it runs.
 
S

Sullivan WxPyQtKinter

I see. I once was a VB programmer. In VB, the current directory is
always set to where the module locates before it runs.
 

Ask a Question

Want to reply to this thread or ask your own question?

You'll need to choose a username for the site, which only take a couple of moments. After that, you can post your question and our members will help you out.

Ask a Question

Members online

No members online now.

Forum statistics

Threads
473,769
Messages
2,569,580
Members
45,054
Latest member
TrimKetoBoost

Latest Threads

Top