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
Author by
Paga
Updated on June 04, 2022Comments
-
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 about 5 yearsPlease post your code as text, not as an image.
-
balderman about 5 yearsBefore 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 about 5 yearsI 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 about 5 yearsPossible duplicate of Telling Python to save a .txt file to a certain directory on Windows and Mac
-
Paga about 5 yearsthanks for the correcting, i am new to python and english
-
-
Paga about 5 yearsoh, i change "" to '' and it works although i don't know the reason. thanks for solving the problem