Reputation: 41
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?
Upvotes: 1
Views: 1622
Reputation: 25
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')
Upvotes: 1
Reputation: 5757
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')
Upvotes: 1