Search code examples
pythonpython-3.xdataframepyqt5export-to-csv

Export two separate dataframes, as csv, to two separate fixed file names but with variable paths


I read, manipulate and now want to export two separate dataframes to .csv. I us QtWidget to select the path.

For my Export I have:

from PyQt5 import QtWidgets, uic
export_file_path, _ = QtWidgets.QFileDialog.getSaveFileName(None, "Select File", "", "Line Files (*.csv)")   
df_Sum.to_csv(export_file_path,index=False) 
export_file_path, _ = QtWidgets.QFileDialog.getSaveFileName(None, "Select File", "", "Line Files (*.csv)")  
df_QC.to_csv(export_file_path,index=False) 

This works, but seems a basic way of doing it. I'd like to choose the export_file_path once and then use the path for both files using a fixed file name for each, e.g. export_file_path"df_Sum.csv" and export_file_path"df_QC.csv"


Solution

  • Using QFileDialog.getExistingDirectory suggested in Comment 1 worked well, but I then realised if I was writing to the same directory as I had opened the initial file from, I could use Comment 2's suggestion and strip the directory path from the open file dialog as save myself a step.

    import_file, _ = QtWidgets.QFileDialog.getOpenFileName(None, "Select File", "", "Line Files (*.csv)") # Ask for file
    ##Do some stuff and make 2 dataframes
    
    #Save both
    Export_Directory=os.path.dirname(import_file) #Get path name from import_file path
    Sum_Name='QC_Summary.csv'
    QC_Name='QC_Log.csv'
    Complete_Sum=os.path.join(Export_Directory,Sum_Name)
    Complete_Log=os.path.join(Export_Directory,QC_Name)
    df_Sum.to_csv(Complete_Sum,index=False)
    df_QC.to_csv(Complete_Log,index=False)