[英]What does local relative filename means in Python?
我发现,要处理文件名给定的文件,我需要做
import os
dir = os.path.dirname(__file__)
filename = os.path.join(dir, '/relative/path/to/file/you/want')
要么
import os
dir = os.getcwd()
filename = os.path.join(dir, '/relative/path/to/file/you/want')
但是如果我这样做
filename = 'myfile.txt'
那么将在哪里寻找该文件?
简短的答案:在当前工作目录中。
长答案:
来自https://docs.python.org/2/library/stdtypes.html#bltin-file-objects
文件对象是使用C的stdio包实现的
从https://docs.python.org/2/library/functions.html#open
前两个参数与stdio的fopen()相同:name是要打开的文件名
因此,这可以通过查看stdio
文档来解决:
从http://www.cplusplus.com/reference/cstdio/fopen/
filename
C字符串,包含要打开的文件的名称。
其值应遵循运行环境的文件名规范,并且可以包含路径(如果系统支持)。
“正在运行的环境的规范”意味着它将解释该环境,就像您键入从中(又名cwd)运行文件的路径一样。
例如,如果我有一个位于~/Desktop/temp.py
中的脚本,其内容为:
f = open("log.txt", 'r')
print "success opening"
f.close()
并且我有一个文件位于~/Desktop/log.txt
,我得到以下输出:
~/Desktop $ python temp.py
success opening
但是,如果我cd ..
然后重试:
~ $ python ~/Desktop/temp.py
Traceback (most recent call last):
File "/home/whrrgarbl/Desktop/temp.py", line 1, in <module>
f = open("log.txt", 'r')
IOError: [Errno 2] No such file or directory: 'log.txt'
只是为了验证:
~ $ touch log.txt
~ $ python ~/Desktop/temp.py
success opening
因此,您可以看到它正在尝试相对于我运行脚本的目录(而不是脚本所在的目录)打开它。
创建了一个简单的python脚本( open.py
)并使用strace
运行它。
剧本:
#!/usr/bin/env python
with open('myfile.txt', 'r') as fd:
pass
strace ./open.py
命令: strace ./open.py
这显示给我(仅显示相关部分):
read(3, "#!/usr/bin/env python\n\nwith ope"..., 4096) = 70
read(3, "", 4096) = 0
brk(0x23a2000) = 0x23a2000
close(3) = 0
munmap(0x7f7f97dc3000, 4096) = 0
open("myfile.txt", O_RDONLY) = -1 ENOENT (No such file or directory)
write(2, "Traceback (most recent call last"..., 35Traceback (most recent call last):
) = 35
write(2, " File \"./open.py\", line 3, in <"..., 40 File "./open.py", line 3, in <module>
) = 40
查看open
系统调用即可获得python脚本中提供的路径。 open
将尝试在当前工作目录中打开该文件,该文件是运行该程序的位置。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.