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?

1

2 Answers 2

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') 
Sign up to request clarification or add additional context in comments.

2 Comments

well you already saved parent_dir so you can just do parent_dir / f"{parent_dir.name}_all_files.tex"
Also note that the parent is not necessary. OP wants to create the file in the given directory, with its name as the prefix
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') 

1 Comment

your edit does not work. Gives --> FileNotFoundError: [Errno 2] No such file or directory:

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.