[英]Python: name folder and file with variable name
I'm trying to create python script that will make folder with variable name and .csv file inside that folder with variable name included.我正在尝试创建 python 脚本,该脚本将在包含变量名称的文件夹中创建带有变量名称的文件夹和 .csv 文件。
import pathlib
import csv
name = input()
pathlib.Path(name).mkdir(parents=True, exist_ok=True)
csvfile = open(name/name+"1day.csv", 'w', newline='')
The name/name
is you are trying to devide name by name. name/name
是您试图按名称划分名称。 the /
is not in a string but an operator. /
不在字符串中,而是在运算符中。 There are two options to solve this.有两种选择可以解决这个问题。
Make the /
string使/
字符串
csvfile = open(name+"/"+name+"1day.csv", 'w', newline='')
However, this option will cause issue if you want it to run in windows and Linux .但是,如果您希望它在 windows 和 Linux 中运行,则此选项会导致问题。 So the option two is an notch up.所以选项二是一个档次。
Use os.path.join()使用 os.path.join()
You have to import the os and use the the join to create a whole path.您必须导入 os 并使用连接来创建整个路径。 you script will look like the following您的脚本将如下所示
import pathlib import csv import os # <--- new line name = input() pathlib.Path(name).mkdir(parents=True, exist_ok=True) csvfile = open(os.path.join(name, name+"1day.csv"), 'w', newline='') # <--- changed one.
The os.path.join
will ensure to use right one ( /
or \\
) depending on the OS you are running. os.path.join
将确保使用正确的一个( /
或\\
),具体取决于您正在运行的操作系统。
I think you're almost there.我想你快到了。 Try尝试
from pathlib import Path
import csv
name = input()
path = Path(name)
path.mkdir(parents=True, exist_ok=True)
csvfile = open(path / (name + "1day.csv"), 'w', newline='')
instead.反而。
The Path
class is almost always the only thing you need from pathlib
, so you don't need to import the full pathlib
. Path
类几乎总是您需要从pathlib
获得的唯一pathlib
,因此您无需导入完整的pathlib
。 If possible, I'd avoid using both, os
and pathlib
, at the same time for working with paths (not always possible, I know, but in most cases).如果可能,我会避免同时使用os
和pathlib
来处理路径(我知道并不总是可行,但在大多数情况下)。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.