0

Is there any standard function or method in python that reads all files from the directory where the python source program is located? Example: Let be the follow code bellow:

import glob, os
from os.path import isfile

def namesARCHIVES(): 
    listNames = []
    os.chdir(r"C:\Users\author\archives")
    for file in glob.glob("*.txt"):
        listNames.append(file)

The method os.chdir(r"C:\Users\author\archives") "reads" the directory that contains all the files I need. The python file you compile is in the same folder. Is there any method that does not need to enter the directory of the files as they are in the same folder as the source code? I don't know if it was well explained

Simone
  • 19
  • 5
  • 2
    Does this answer your question? [How do I list all files of a directory?](https://stackoverflow.com/questions/3207219/how-do-i-list-all-files-of-a-directory) – ggorlen Jan 10 '20 at 23:20
  • why not use ```cwd = os.getcwd()```? – Shay Lempert Jan 10 '20 at 23:22
  • _The method os.chdir(r"C:\Users\author\archives") "reads" the directory that contains all the files I need._ I know you put quotes around the word "reads", but even as an approximation I'm not sure I understand how that makes sense. _Is there any method that does not need to enter the directory of the files as they are in the same folder as the source code?_ All of them, I imagine. This seems like a case of the [XY Problem](https://meta.stackexchange.com/q/66377/628382) to me, can you explain what you actually need to do? – AMC Jan 11 '20 at 02:09
  • Also, variable and function names should follow the `lower_case_with_underscores` style. – AMC Jan 11 '20 at 02:12

1 Answers1

0

The path name of the current source file is stored in the __file__ variable, with which you can use os.path.dirname to obtain the directory that the source file is located. Also, glob.glob returns a list already, so you don't need to iterate through it just to append the items to another list:

listNames = glob.glob(os.path.join(os.path.dirname(__file__), '*.txt'))
blhsing
  • 91,368
  • 6
  • 71
  • 106