Python中的本地相对文件名是什么意思?

2024-04-20 00:39:26 发布

您现在位置: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'

那么在哪里找这个文件呢?你知道吗


Tags: 文件topathimportyouos文件名dir
2条回答

创建了一个简单的python脚本(open.py),并用strace运行它。你知道吗

剧本:

#!/usr/bin/env python

with open('myfile.txt', 'r') as fd:
    pass

Strace命令: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将尝试打开当前工作目录中的文件,该目录是运行程序的位置。你知道吗

简答:在当前工作目录中。你知道吗

长答案:

https://docs.python.org/2/library/stdtypes.html#bltin-file-objects

File objects are implemented using C’s stdio package

https://docs.python.org/2/library/functions.html#open

The first two arguments are the same as for stdio‘s fopen(): name is the file name to be opened

因此,可以通过查看stdio的文档来回答这个问题:

http://www.cplusplus.com/reference/cstdio/fopen/

filename

C string containing the name of the file to be opened.

Its value shall follow the file name specifications of the running environment and can include a path (if supported by the system).

“运行环境的规范”意味着它将对其进行解释,就好像您输入了运行文件的路径,也就是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

因此,您可以看到它试图相对于我运行脚本的目录打开它,而不是相对于脚本所在的目录。你知道吗

相关问题 更多 >