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)
CodePudding user response:
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:
CodePudding user response:
You're trying to concatenate (with the /
operator) a Path
object (Path.cwd()
) and a _io.TextIOWrapper
object (Path(f"{file_name}.txt").open('w')
). You want to call .open()
on the concatenated path instead, using parentheses ()
:
with (Path.cwd() / Path(f"{file_name}.txt")).open('w') as file:
file.write("This works!")