Python 如何使用程序所在的当前文件夹?

Python 如何使用程序所在的当前文件夹?,python,Python,当我打开一个文件时,我必须指定它所在的目录。有没有办法指定使用当前目录而不是写出路径名?我正在使用: source = os.listdir("../mydirectory") 但该程序只有放在名为“mydirectory”的目录中才能工作。我希望程序在它所在的目录中工作,不管名称是什么 def copyfiles(servername): source = os.listdir("../mydirectory") # directory where original configs

当我打开一个文件时,我必须指定它所在的目录。有没有办法指定使用当前目录而不是写出路径名?我正在使用:

source = os.listdir("../mydirectory")
但该程序只有放在名为“mydirectory”的目录中才能工作。我希望程序在它所在的目录中工作,不管名称是什么

def copyfiles(servername):

    source = os.listdir("../mydirectory") # directory where original configs are located
    destination = '//' + servername + r'/c$/remotedir/' # destination server directory
    for files in source:
        if files.endswith("myfile.config"):
            try:
                os.makedirs(destination, exist_ok=True)
                shutil.copy(files,destination)
            except:

代表当前目录。

代表当前目录。

尝试:

os.listdir('./')
或:

尝试:

或:

这是一个版本:

如果您愿意:

注意:这通常与当前工作目录不同

os.getcwd()  #  or '.'
是当前python文件的文件名
此处
是python文件所在目录的路径。

这是一个版本:

如果您愿意:

注意:这通常与当前工作目录不同

os.getcwd()  #  or '.'

是当前python文件的文件名
这里
现在是python文件所在目录的路径。

为了完整性,值得一提的是,如果相对路径不起作用,那么总会有
os.getcwd()
。为了完整性,值得一提的是,如果相对路径不起作用,那么总会有
os.getcwd()
。值得注意的是,如果您使用的是Python3.x,只需使用
os.listdir()
,而无需任何参数。另外,
/
是不必要的:)值得注意的是,如果您使用的是Python3.x,只需使用
os.listdir()
,而无需任何参数。另外,
/
是不必要的:)的可能重复
import os.path
HERE = os.path.dirname(__file__)
source = os.listdir(os.path.join(HERE, "../mydirectory"))
os.getcwd()  #  or '.'