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='')
CodePudding user response:
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
/stringcsvfile = 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 followingimport 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.joinwill ensure to use right one (/or\) depending on the OS you are running.
CodePudding user response:
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).
