TUX One
TUX One

Reputation: 167

Save file in a specific folder

I would like to save a CSV file in a specific folder, but I can't find anywhere how to do it... this is the code

# Writing on a CSV FILE
                fileToWrite = open(f"{userfinder}-{month}-{year}.csv', "a")
                fileToWrite.write('Subject,Start Date,Start Time,End Date,End Time,All Day Event,Description\n')
                fileToWrite.write(f'{string1}{tagesinfo2},{soup_datum},{soup_dienstbegin},{soup_datum},{soup_dienstende},,Kommentar: {soup_kommentar} Schiff: {b} Funktion: {soup_funktion} Schichtdauer: {soup_schichtdauer} Bezahlte Zeit: {soup_bezahltezeit} Mannschaft: {crew_list2}\n')
                fileToWrite.close()
                print(f'Datum: {soup_datum} Dienst: {string1}{tagesinfo2} --> Mannschaft: {crew_list2} --> OK')

Upvotes: 1

Views: 4464

Answers (1)

Eli Harold
Eli Harold

Reputation: 2301

You just have to change the working directory with os.chdir(path):

import os
path = '/Users/user/folder/example sub folder'
os.chdir(path)

#your code here

or, as mentioned in the comments, you can use:

myfolder = "c:/foo/bar/" 
fileToWrite = open(f"{myfolder}/{userfinder}-{month}-{year}.csv", "a")

#in this case the path is "{myfolder}/{userfinder}-{month}-{year}"

This option includes the path when opening (only affects the one file) whereas os.chdir() changes the directory for everything (what I use personally for all of my projects, which are small). If you don't want to change your folder for all files created and read, use the second option; but when you want a python file to affect every file in a distant location I would use os.chdir().

Upvotes: 1

Related Questions