Search code examples
pythonpython-3.xpathfilepath

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.

import pathlib
import csv
name = input()
pathlib.Path(name).mkdir(parents=True, exist_ok=True)
csvfile = open(name/name+"1day.csv", 'w', newline='')

Solution

  • 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.

    1. 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.

    2. 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.