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)

2 Answers 2

5

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
Sign up to request clarification or add additional context in comments.

Comments

0
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__)

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.