0

What I would like to do is create a variable homedir that is set to the home folder script. How do I do this? Like say the script is located in C:\blah\, I would want homedir to be assigned to that.

homedir = (current directory)
pdfList = []

def getfiles():
    directory = os.listdir(homedir)
    for file in directory:
        if "pdf" in file:
            pdfList.append(file)
4

2 回答 2

5

__file__module 属性包含脚本位置,但它可能是相对的。下面的文件是c:\test\x.py.

import os
print(__file__)
homedir = os.path.abspath(os.path.dirname(__file__))
print(homedir)

输出:

.\x.py
c:\test
于 2013-03-24T18:32:10.220 回答
0
homedir = '.'

或者

import os
homedir = os.getcwd()

将导致os.listdir(homedir)列出当前工作目录(即执行脚本的目录)中的文件(和子目录)。请注意,这不一定与包含脚本的目录相同。对于该目录使用

import os
homedir = os.path.dirname(__file__)
于 2013-03-24T18:27:37.563 回答