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

5
  • 1
    Please post your code as text, not as an image. Mar 1, 2019 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 1, 2019 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 1, 2019 at 12:27
  • thanks for the correcting, i am new to python and english
    – Paga
    Mar 1, 2019 at 13:22

3 Answers 3

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

Your Answer

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

Not the answer you're looking for? Browse other questions tagged or ask your own question.