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
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'))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.