简体   繁体   中英

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)

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!")

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:

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM