I'm trying to create python script that will make folder with variable name and .csv file inside that folder with variable name included.
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. 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 . So the option two is an notch up.
Use os.path.join()
You have to import the os and use the the join to create a whole path. 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.
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
. 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).
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.