1

I am creating files dynamically in different folders, like so:

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

Which gives me:

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

But because I am creating files with the same name in many folders, I want to distinguish them by adding the folder's name as a prefix, to get:

"a/b/c/c_file.text"

How can I get that?

Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Parag
  • 41
  • 8
  • 1
    Does this answer your question? [Get folder name of the file in Python](https://stackoverflow.com/questions/33372054/get-folder-name-of-the-file-in-python) – Tomerikoo Sep 24 '20 at 11:51

2 Answers2

1
texfile = os.path.join(curr_dir, 'all_files.tex')

only concatenates the current directory path to your filename.

You should have something like:

texfile = os.path.join(curr_dir, os.path.basename(curr_dir)+'_all_files.tex')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
Ritesh
  • 15
  • 7
  • your edit does not work. Gives --> FileNotFoundError: [Errno 2] No such file or directory: – Parag Sep 24 '20 at 11:38
1

Try the pathlib package instead:

>>> 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')
Tomerikoo
  • 18,379
  • 16
  • 47
  • 61
abhilb
  • 5,639
  • 2
  • 20
  • 26
  • well you already saved `parent_dir` so you can just do `parent_dir / f"{parent_dir.name}_all_files.tex"` – Tomerikoo Sep 30 '20 at 08:01
  • Also note that the `parent` is not necessary. OP wants to create the file in the given directory, with its name as the prefix – Tomerikoo Sep 30 '20 at 08:17