0

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='')
1
  • 1
    use os.path.join() module to concatenate path instead of doing it they way you are doing. import os and open(os.path.join(name, name + "1day.csv"), "w", newline="") Commented Nov 15, 2021 at 10:52

2 Answers 2

1

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.

Sign up to request clarification or add additional context in comments.

Comments

1

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

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.