jumbopap
jumbopap

Reputation: 4147

Setting directory to path of script

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)

Upvotes: 0

Views: 98

Answers (2)

unutbu
unutbu

Reputation: 880777

homedir = '.'

or

import os
homedir = os.getcwd()

will cause os.listdir(homedir) to list the files (and subdirectories) in the current working directory (i.e. the directory from which the script was executed). Note that this is NOT necessarily the same as the directory which contains the script. For that directory use

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

Upvotes: 0

Mark Tolonen
Mark Tolonen

Reputation: 178199

The __file__ module attribute contains the script location, but it may be relative. The file below is c:\test\x.py.

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

Output:

.\x.py
c:\test

Upvotes: 5

Related Questions