简体   繁体   English

使用 pathlib 库在 Python 中自定义文件命名

[英]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.使用 os 库,您可以在创建文件时将变量作为文件名传递给 os.path.join。

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?有什么方法可以使 pathlib 库具有相同的功能吗? 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) (使用 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') ).您正在尝试连接(使用/运算符)一个Path对象( Path.cwd() )和一个_io.TextIOWrapper对象( Path(f"{file_name}.txt").open('w') )。 You want to call .open() on the concatenated path instead, using parentheses () :您想在连接的路径上调用.open() ,而不是使用括号()

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:您需要使用括号,否则它将在将路径添加到一起之前执行.open()方法:

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:

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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