在python中构建完整路径文件名,

时间:2022-09-01 22:17:10

I need to pass a file path name to a module which creates a report document as pdf,html etc.How do I build the file path name from a directory name,base file name and a fileformat string ?

我需要将文件路径名传递给一个模块,该模块将报告文档创建为pdf、html等等。如何从目录名、基文件名和文件格式字符串构建文件路径名?

The directory may or may not exist at the time of call

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

for example

例如

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

I need to create a string '/home/me/dev/my_reports/daily_report.pdf'

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

concatenating the pieces manually didn't seem to be a good way. I tried os.path.join

手工连接各个部分似乎不是一个好方法。我试着os.path.join

join(dir_name,base_filename,format)

but it gives

但它给

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

4 个解决方案

#1


166  

This works fine:

这工作正常:

os.path.join(dir_name, base_filename + "." + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote), because they are always separated from the rest of the name by the same dot character, on every OS.

请记住,os.path.join()之所以存在,仅仅是因为不同的操作系统使用不同的路径分隔符。它消除了这种差异,因此跨平台代码不必为每个操作系统的特殊情况而混乱。对于文件名“extensions”(请参阅脚注),不需要这样做,因为在每个操作系统中,它们总是通过相同的点字符与其他名称分隔开。

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

如果使用一个函数会让你感觉更好(而且你喜欢不必要地使代码复杂化),你可以这样做:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

如果你喜欢保持你的代码干净,只要在后缀中包含点:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

Footnote: There is no such thing as a file name "extension" on non-Micorsoft operating systems. Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

脚注:在非micorsoft操作系统上不存在文件名“扩展”之类的东西。它在Windows上的应用来自MS-DOS和FAT,它们是从CP/M那里借来的,CP/M已经死了几十年了。我们很多人习惯看到的点加3个字母只是其他所有现代操作系统文件名的一部分,在这些操作系统中,它没有内置的含义。

#2


19  

Um, why not just:

嗯,为什么不直接:

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

#3


11  

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

如果您有幸运行Python 3.4+,可以使用pathlib:

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

#4


0  

Just use os.path.join to join your path with the filename and extension. Use sys.argv to access arguments passed to the script when executing it:

只使用os.path。使用文件名和扩展名连接路径。使用系统。argv在执行时传递给脚本的参数:

#!/usr/bin/env python3
# coding: utf-8

# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv

import os.path
import sys

basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'


def read_fid(filename):
    fid = nc.MFDataset(filename,'r')
    fid.close()
    return fid

def read_var(file, varname):
    fid = nc.Dataset(file, 'r')
    out = fid.variables[varname][:]
    fid.close()
    return out


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Please specify a year')

    else:
        filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
        time = read_var(ncf, 'time')
        lat = read_var(ncf, 'lat')
        lon = read_var(ncf, 'lon')
        soil = read_var(ncf, 'soilw')

Simply run the script like:

简单地运行脚本:

   # on windows-based systems
   python script.py year

   # on unix-based systems
   ./script.py year

#1


166  

This works fine:

这工作正常:

os.path.join(dir_name, base_filename + "." + filename_suffix)

Keep in mind that os.path.join() exists only because different operating systems use different path separator characters. It smooths over that difference so cross-platform code doesn't have to be cluttered with special cases for each OS. There is no need to do this for file name "extensions" (see footnote), because they are always separated from the rest of the name by the same dot character, on every OS.

请记住,os.path.join()之所以存在,仅仅是因为不同的操作系统使用不同的路径分隔符。它消除了这种差异,因此跨平台代码不必为每个操作系统的特殊情况而混乱。对于文件名“extensions”(请参阅脚注),不需要这样做,因为在每个操作系统中,它们总是通过相同的点字符与其他名称分隔开。

If using a function anyway makes you feel better (and you like needlessly complicating your code), you can do this:

如果使用一个函数会让你感觉更好(而且你喜欢不必要地使代码复杂化),你可以这样做:

os.path.join(dir_name, '.'.join((base_filename, filename_suffix)))

If you prefer to keep your code clean, simply include the dot in the suffix:

如果你喜欢保持你的代码干净,只要在后缀中包含点:

suffix = '.pdf'
os.path.join(dir_name, base_filename + suffix)

Footnote: There is no such thing as a file name "extension" on non-Micorsoft operating systems. Its presence on Windows comes from MS-DOS and FAT, which borrowed it from CP/M, which has been dead for decades. That dot-plus-three-letters that many of us are accustomed to seeing is just part of the file name on every other modern OS, where it has no built-in meaning.

脚注:在非micorsoft操作系统上不存在文件名“扩展”之类的东西。它在Windows上的应用来自MS-DOS和FAT,它们是从CP/M那里借来的,CP/M已经死了几十年了。我们很多人习惯看到的点加3个字母只是其他所有现代操作系统文件名的一部分,在这些操作系统中,它没有内置的含义。

#2


19  

Um, why not just:

嗯,为什么不直接:

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

#3


11  

If you are fortunate enough to be running Python 3.4+, you can use pathlib:

如果您有幸运行Python 3.4+,可以使用pathlib:

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

#4


0  

Just use os.path.join to join your path with the filename and extension. Use sys.argv to access arguments passed to the script when executing it:

只使用os.path。使用文件名和扩展名连接路径。使用系统。argv在执行时传递给脚本的参数:

#!/usr/bin/env python3
# coding: utf-8

# import netCDF4 as nc
import numpy as np
import numpy.ma as ma
import csv as csv

import os.path
import sys

basedir = '/data/reu_data/soil_moisture/'
suffix = 'nc'


def read_fid(filename):
    fid = nc.MFDataset(filename,'r')
    fid.close()
    return fid

def read_var(file, varname):
    fid = nc.Dataset(file, 'r')
    out = fid.variables[varname][:]
    fid.close()
    return out


if __name__ == '__main__':
    if len(sys.argv) < 2:
        print('Please specify a year')

    else:
        filename = os.path.join(basedir, '.'.join((sys.argv[1], suffix)))
        time = read_var(ncf, 'time')
        lat = read_var(ncf, 'lat')
        lon = read_var(ncf, 'lon')
        soil = read_var(ncf, 'soilw')

Simply run the script like:

简单地运行脚本:

   # on windows-based systems
   python script.py year

   # on unix-based systems
   ./script.py year