我正在不同的文件夹中动态创建文件,如下所示:
curr_dir = "/a/b/c"
filename = os.path.join(curr_dir, 'file.text')
哪个给我:
"/a/b/c/file.text"
但是因为我要在许多文件夹中创建具有相同名称的文件,所以我想通过添加文件夹名称作为前缀来区分它们,以获得:
"a/b/c/c_file.text"
我该怎么办?
答案 0 :(得分:1)
请尝试使用pathlib
软件包:
>>> from pathlib import Path
>>> Path()
WindowsPath('.')
>>> Path().absolute()
WindowsPath('C:/Users/p00200284/test')
>>> Path().absolute().parent
WindowsPath('C:/Users/p00200284')
>>> Path().absolute().parent / "all_files.tex"
WindowsPath('C:/Users/p00200284/all_files.tex')
>>> str(Path().absolute().parent / "all_files.tex")
'C:\\Users\\p00200284\\all_files.tex'
>>> Path().absolute().parent.name
'p00200284'
>>> f"{Path().absolute().parent.name}_all_files.tex"
'p00200284_all_files.tex'
>>> parent_dir = Path().absolute().parent
>>> parent_dir / f"{Path().absolute().parent.name}_all_files.tex"
WindowsPath('C:/Users/p00200284/p00200284_all_files.tex')
答案 1 :(得分:0)
texfile = os.path.join(curr_dir, 'all_files.tex')
仅将当前目录路径连接到您的文件名。
您应该有类似的内容:
texfile = os.path.join(curr_dir, curr_dir+'_all_files.tex')