Search code examples
pythonfilerenamenaming

Is there a way to use the name of the imported file in naming a new created file?


In my program I import a certain file, at the end I create a file in which I save the outputs. I would like to use the name of the imported file (with some additions) as the name of the newly created file.

Since I have a large amount of files to import, I would like to do this in order to have a better overview of which files were created based on which files.

For example: I open a file with file=open(‘summer.txt’) and I would like to use the 'summer' of the original file and just add the year, the name of the new file would be ‘summer2020.txt’.

I would like to automatically detect the name of the imported file, add the year and that would be the name of my new file. (the addition to the name ('2020') would be the same for every opened file)

I’ m still new to python, so I don‘t know if this is possible or if there is a better way of doing it. Thank you very much for any help!


Solution

  • If you are using Python 3.9, you can use pathlib and the new with_stem method

    file_path=Path('summer.txt')
    new_file_path = file_path.with_stem(file_path.stem+'2020')
    

    Advantage of using pathlib is that it supports multiple platforms (win/osx/linux) and their different ways of specifying paths. Also allows you to easily split the file name in to the stem summer and suffix .txt.

    For versions of python like 3.6.5, you can do the following instead

    new_file_path = file_path.with_name(f"{file_path.stem}2020{file_path.suffix}")