简体   繁体   中英

how to write csv file into specific folder

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

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:
   [...]

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

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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM