2

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

Torxed
  • 22,866
  • 14
  • 82
  • 131
Paga
  • 103
  • 1
  • 2
  • 9
  • 1
    Please post your code as **text**, not as an image. – Thierry Lathuille Mar 01 '19 at 12:19
  • 1
    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")' – balderman Mar 01 '19 at 12:21
  • 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 Mar 01 '19 at 12:27
  • Possible duplicate of [Telling Python to save a .txt file to a certain directory on Windows and Mac](https://stackoverflow.com/questions/8024248/telling-python-to-save-a-txt-file-to-a-certain-directory-on-windows-and-mac) – Torxed Mar 01 '19 at 12:28
  • thanks for the correcting, i am new to python and english – Paga Mar 01 '19 at 13:22

3 Answers3

1

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
Banneisen
  • 33
  • 5
0

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:
   [...]
Placeprom
  • 64
  • 7
  • 1
    oh, i change "" to '' and it works although i don't know the reason. thanks for solving the problem – Paga Mar 01 '19 at 13:49
0

You can add a check for the directory like this just before open statement

dir_path = 'folder_to_save_csv_file_in'
if not os.path.isdir(dir_path):
    os.makedirs(dir_path)

with open('{file_path}.csv'.format(file_path=os.path.join(dir_path, file_name), 'w+') as csv_file:
    ....
sanster_23
  • 800
  • 10
  • 17