我需要将文件路径名传递给一个模块。如何从目录名、基本文件名和文件格式字符串构建文件路径?

该目录在调用时可能存在,也可能不存在。

例如:

dir_name='/home/me/dev/my_reports'
base_filename='daily_report'
format = 'pdf'

我需要创建一个字符串'/home/me/dev/my_reports/daily_report.pdf'

手动连接这些片段似乎不是一个好方法。我尝试了os.path.join:

join(dir_name,base_filename,format)

但是它给出了

/home/me/dev/my_reports/daily_report/pdf

当前回答

为了更好地理解,添加以下代码:

import os
def createfile(name, location, extension):
    print(name, extension, location)
    #starting creating a file with some dummy contents
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "a")
    f.write("Your contents!! or whatever you want to put inside this file.")
    f.close()
    print("File creation is successful!!")

def readfile(name, location, extension):
    #open and read the file after the appending:
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "r")
    print(f.read())

#pass the parameters here
createfile('test','./','txt')
readfile('test','./','txt')

其他回答

如果你足够幸运地运行Python 3.4+,你可以使用pathlib:

>>> from pathlib import Path
>>> dirname = '/home/reports'
>>> filename = 'daily'
>>> suffix = '.pdf'
>>> Path(dirname, filename).with_suffix(suffix)
PosixPath('/home/reports/daily.pdf')

在基本文件名中添加格式不是更好吗?

dir_name='/home/me/dev/my_reports/'
base_filename='daily_report.pdf'
os.path.join(dir_name, base_filename)

为什么不直接:

>>> import os
>>> os.path.join(dir_name, base_filename + "." + format)
'/home/me/dev/my_reports/daily_report.pdf'

为了更好地理解,添加以下代码:

import os
def createfile(name, location, extension):
    print(name, extension, location)
    #starting creating a file with some dummy contents
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "a")
    f.write("Your contents!! or whatever you want to put inside this file.")
    f.close()
    print("File creation is successful!!")

def readfile(name, location, extension):
    #open and read the file after the appending:
    path = os.path.join(location, name + '.' + extension)
    f = open(path, "r")
    print(f.read())

#pass the parameters here
createfile('test','./','txt')
readfile('test','./','txt')
from pathlib import Path

# Build paths inside the project like this: BASE_DIR / 'subdir'.

BASE_DIR = Path(__file__).resolve().parent.parent
TEMPLATE_PATH = Path.joinpath(BASE_DIR,"templates")
print(TEMPLATE_PATH)