pythonoperating-systemcwd

Why does my code not write to my file path indicated in write to CSV?


I have a dataframe. I want to write it to a csv in a specific path. I attempted-

import os
df3
out_path =  ('//gg-data-share/jobs/Compliance')

df3.to_csv(out_path + 'CombinedEscalations.csv')

the script runs successfully, however, it writes to //gg-data-share/jobs instead of within the Compliance folder and weirdly it saves the file with a different name:

'ComplianceCombinedEscalations.csv' in the jobs folder instead of the subfolder.

Am I doing something wrong in out_path?


Solution

  • There appears to be an issue in the way you are adding the two strings together in your to_csv() argument.

    When you add your strings together, you get a result as demonstrated below.

    string_1 = '//gg-data-share/jobs/Compliance'
    string_2 = 'CombinedEscalations.csv'
    string_sum = string_1 + string_2
    
    string_sum
    
    # Result
    '//gg-data-share/jobs/ComplianceCombinedEscalations.csv'
    

    This is because adding strings has no regard for the format in which you created the strings in the first place. Thus, you need to make sure that when you add them together you preserve any file-structure formatting you intended.

    To have your DataFrame saved to a Compliance subfolder with the name CombinedEscalations.csv, try the following.

    out_path =  '//gg-data-share/jobs/Compliance' # this is a folder
    
    df3.to_csv(out_path + '/CombinedEscalations.csv') # add a '/'