没有这样的文件或目录错误
我遇到的错误是:
Traceback (most recent call last):
File "E:\stuff\module.py", line 91, in <module>
f = open('E:/stuff/log.txt')
IOError: [Errno 2] No such file or directory: 'E:/stuff/log.txt'
这是我的代码:
f = open('E:/stuff/log.txt')
E:/stuff/log.txt
这个文件是存在的。我可以在Windows资源管理器中找到并打开它,那为什么我在代码里打不开呢?
补充说明:
这是我用DIR命令得到的输出:
C:\Documents and Settings\Administrator>dir e:\stuff
Volume in drive E has no label.
Volume Serial Number is 5660-4957
Directory of e:\stuff
23. 10. 2010 09:26 <DIR> .
23. 10. 2010 09:26 <DIR> ..
19. 10. 2010 20:07 385 index.py
23. 10. 2010 16:12 1 954 module.py
22. 10. 2010 19:16 8 335 backprop.py
19. 10. 2010 20:54 1 307 backprop-input.gif
19. 10. 2010 01:48 310 HelloWorld.kpf
23. 10. 2010 15:47 0 log.txt.txt
6 File(s) 12 291 bytes
2 Dir(s) 8 795 586 560 bytes free
C:\Documents and Settings\Administrator>dir e:\
Volume in drive E has no label.
Volume Serial Number is 5660-4957
Directory of e:\
16. 10. 2010 13:32 <DIR> development-tools
23. 10. 2010 09:26 <DIR> stuff
0 File(s) 0 bytes
2 Dir(s) 8 795 586 560 bytes free
我是在命令提示符下这样运行Python脚本的:
python E:\stuff\module.py
8 个回答
1
使用 os.path.join()
来定义你的路径名称
root="E:\\"
mylog = os.path.join(root,"stuff","log.txt") # or log.txt.txt as seen in your dir output
f = open(mylog)
...
f.close()
4
看看“dir”命令的输出中的这一行:
23. 10. 2010 15:47 0 log.txt.txt
你要找的文件叫“log.txt.txt”,而不是“log.txt”。我发现很多人会遇到这种情况,通常是因为他们把Windows文件管理器设置成不显示已知的文件扩展名,然后在添加或修改扩展名时就会出错。我建议大家把这个设置关掉。你可以在“查看”->“文件夹选项”里找到这个选项。
13
首先,从上面的内容来看,Windows系统是完全支持的。
其次:如果你查看你的文件,会发现它不是log.txt,而是log.txt.txt……在你的图形文件夹查看器中,你可能会看到它显示为“log.txt”,但实际上它的完整名称是“log.txt.txt”。这是因为图形界面隐藏了已知文件类型的扩展名。
我建议你关闭这个隐藏功能——你可以去文件夹选项里找,应该有一个叫“隐藏已知文件类型的扩展名”(或者类似的选项)的设置。