当我打开一个文件时,我必须指定它所在的目录。有没有办法指定使用当前目录而不是写出路径名?我使用的是:
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:发布于 2017-06-24 01:01:57
'.'代表当前目录。
发布于 2017-06-24 01:03:17
这是一个pathlib版本:
from pathlib import Path
HERE = Path(__file__).parent
source = list((HERE /  "../mydirectory").iterdir())如果您更喜欢os.path
import os.path
HERE = os.path.dirname(__file__)
source = os.listdir(os.path.join(HERE, "../mydirectory"))注意:这通常与当前的工作目录不同
os.getcwd()  #  or '.'__file__是当前python文件的文件名。HERE现在是您的python文件所在目录的路径。
发布于 2017-06-24 01:03:10
尝试:
os.listdir('./')或者:
os.listdir(os.getcwd())https://stackoverflow.com/questions/44726578
复制相似问题