469,271 Members | 1,431 Online
Bytes | Developer Community
New Post

Home Posts Topics Members FAQ

Post your question to a community of 469,271 developers. It's quick & easy.

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

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.

Mar 11 '06 #1
3 1634
"Sullivan WxPyQtKinter" wrote:
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>

Mar 11 '06 #2
I see. I once was a VB programmer. In VB, the current directory is
always set to where the module locates before it runs.

Mar 11 '06 #3
I see. I once was a VB programmer. In VB, the current directory is
always set to where the module locates before it runs.

Mar 11 '06 #4

This discussion thread is closed

Replies have been disabled for this discussion.

Similar topics

6 posts views Thread by Aubrey Hutchison | last post: by
47 posts views Thread by Michael Scarlett | last post: by
7 posts views Thread by Stuart McGraw | last post: by
4 posts views Thread by Dirk Thierbach | last post: by
108 posts views Thread by Bryan Olson | last post: by
2 posts views Thread by Sullivan WxPyQtKinter | last post: by
reply views Thread by Kurt B. Kaiser | last post: by
852 posts views Thread by Mark Tarver | last post: by
reply views Thread by Rajanikanth Jammalamadaka | last post: by
reply views Thread by zhoujie | last post: by
reply views Thread by suresh191 | last post: by
By using this site, you agree to our Privacy Policy and Terms of Use.