Search code examples
pythonpython-3.xpathlibpython-os

Custom naming of files in Python using pathlib library


With the os library you can pass a variable to os.path.join as a file name when creating the file.

file_name = "file.txt"
folder_with_files = os.getcwd()
with open(os.path.join(folder_with_files,f"{file_name}.txt"),'w') as file:
    file.write("fail")

Is there any way to have the same functionality with the pathlib library? The following, not suprisingly, doesn't work.

with Path.cwd() / Path(f"{file_name}.txt").open('w') as file:
    file.write("fail")

Traceback (most recent call last):
  ...
   with Path.cwd() / Path(f"{file_name}.txt").open('w') as file:
TypeError: unsupported operand type(s) for /: 'WindowsPath' and '_io.TextIOWrapper

(using Python 3.9)


Solution

  • You need to use parenthesis, otherwise it will execute the .open() method before it adds the paths together:

    with (Path.cwd() / Path(f"{file_name}.txt")).open('w') as file:
    

    This will work as well:

    with open(Path.cwd() / Path(f"{file_name}.txt"), 'w') as file: