【问题标题】:Adding folder name as a prefix to the file's name添加文件夹名称作为文件名的前缀
【发布时间】:2020-09-24 11:18:48
【问题描述】:

我在不同的文件夹中动态创建文件,如下所示:

curr_dir = "/a/b/c"
filename = os.path.join(curr_dir, 'file.text')

这给了我:

"/a/b/c/file.text"

但是因为我在很多文件夹中创建同名文件,我想通过添加文件夹名称作为前缀来区分它们,得到:

"a/b/c/c_file.text"

我怎样才能得到它?

【问题讨论】:

标签: python filenames


【解决方案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')

【讨论】:

  • 你已经保存了parent_dir,所以你可以做parent_dir / f"{parent_dir.name}_all_files.tex"
  • 另请注意,parent 不是必需的。 OP希望在给定目录中创建文件,其名称为前缀
【解决方案2】:
texfile = os.path.join(curr_dir, 'all_files.tex')

仅将当前目录路径连接到您的文件名。

你应该有类似的东西:

texfile = os.path.join(curr_dir, os.path.basename(curr_dir)+'_all_files.tex')

【讨论】:

  • 您的编辑无效。给出 --> FileNotFoundError: [Errno 2] No such file or directory:
猜你喜欢
  • 2016-01-17
  • 2015-03-16
  • 1970-01-01
  • 2020-11-10
  • 2011-05-20
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2018-05-13
相关资源
最近更新 更多