how to write csv file into specific folder

13,374

Solution 1

I would simply create the directory and except directory exists error

try:
   os.mkdir("./CSV")
except OSError as e:
   print("Directory exists")

with open("./CSV/" + f + ".csv", newline="") as csvfile:
   [...]

Solution 2

Instead of using os I recommend using the pathlib module. You can create a directory with:

path = Path('path/to/dir')
path.mkdir(parents=True)

to create the directory and all its missing parent dirs. After doing this you can create a file in the new directory with

fpath = (path / 'filename').with_suffix('.csv')
with fpath.open(mode='w+') as csvfile:
    # your csv writer code
Share:
13,374
Paga
Author by

Paga

Updated on June 04, 2022

Comments

  • Paga
    Paga almost 2 years

    i am trying to write several .csv file into one specific directory

    here is my code

    with open(f+'.csv', 'w', newline='') as csvfile:
        writer = csv.writer(csvfile)
    
        writer.writerow(["index", "B", "G", "R"])
    
        for row in rows:
            writer.writerow(row)
    
        writer.writerow(["Mean", mean_b/total_b, mean_g/total_g, mean_r/total_r])
        writer.writerow("STD", np.sqrt(var_b/total_b), np.sqrt(var_g/total_g), np.sqrt(var_r/total_r))
    

    i have created the csv file into the directory which is same as the .py file however i would like to create a directory and create my csv file in it

    i know i need to us os.makedirs() function

    but i don't know whether i have to create the directory first and designate the path for the csv file or i simply put the directory name into the open() function

    please help me

    • Thierry Lathuille
      Thierry Lathuille about 5 years
      Please post your code as text, not as an image.
    • balderman
      balderman about 5 years
      Before you start looping over the files make sure if the folder exists. If its not - create it. You can use 'os.path.isdir("/the_folder_name")'
    • Torxed
      Torxed about 5 years
      I took the liberty of swapping your image for actual text/code. I hope I got all the nuances and spelling correctly. Correct the block if something is out of place.
    • Torxed
      Torxed about 5 years
    • Paga
      Paga about 5 years
      thanks for the correcting, i am new to python and english
  • Paga
    Paga about 5 years
    oh, i change "" to '' and it works although i don't know the reason. thanks for solving the problem