Search code examples
pythoncsvdirectoryfilepath

How to write a daily .csv to a specific filepath


I'm running a program daily and want the .csv is generates to be written to a folder on my C drive. For some reason, I can create the folder and write 1 file but no others are being written. Not getting any errors, just no other files are being written to that folder. Here's the code. Thanks

Code:

CSVdir = r"C:\Users\Maurice\Desktop\Python\New_Project\OptionsData\\OptionsData-{}.csv"
realCSVdir = os.path.realpath(CSVdir)

if not os.path.exists(CSVdir): 
    os.makedirs(CSVdir)
    str1 = "\n".join(data)
    now = datetime.datetime.now() #+ datetime.timedelta(days=1)
    now_str = now.strftime("%Y-%m-%d")

    new_file_name = os.path.join(realCSVdir,'OptionsData-{}.csv'.format(now_str)) 
    new_file = open(new_file_name, 'wb')

    for item in money_list:
        if len(item) != 0 :
            for other_item in item :
                new_file.write(other_item + str1 + new_file)

                new_file.close()

            print("Eureka!")

Solution

  • CSVdir = r"C:\Users\Maurice\Desktop\Python\New_Project\OptionsData\\OptionsData-{}.csv"
    

    should be

    CSVdir = r"C:\Users\Maurice\Desktop\Python\New_Project\OptionsData"
    
    if not os.path.exists(CSVdir): 
        os.makedirs(CSVdir)
    
    # The following lines should be out of if statement.
    
    str1 = "\n".join(data)
    now = datetime.datetime.now() #+ datetime.timedelta(days=1)
    now_str = now.strftime("%Y-%m-%d")
    
    new_file_name = os.path.join(realCSVdir,'OptionsData-{}.csv'.format(now_str)) 
    new_file = open(new_file_name, 'wb')
    
    
    for item in money_list:
        if len(item) != 0 :
            for other_item in item :
                new_file.write(other_item + str1 + new_file)
    
                new_file.close()
    
            print("Eureka!")