Search code examples
pythoncsvpyqt5export-to-csv

How to make copies of an existing csv file using python?


I've designed a GUI with textboxes that take in user input, using python and PyQT5. When they press the submit button on the form, a new copy of an existing csv file must be created. The information the user input must transfer or register onto that new copy.

How can I make a new copy of an already made csv file that contains the necessary headers for certain rows and columns every time the user hits submit?


Solution

  • Here's a simple function to do it using pandas. Assuming the 'new info' is written to the file name, you can substitute 'copy_of' below with that new data.

    If you want to transfer the 'new data' into the headers of your csv, please provide examples of both original header as well as what you would like to add to it.

    def copy_csv(filename):
        import pandas as pd
        df = pd.read_csv('file.csv')
        df.to_csv('copy_of_' + 'file.csv')
    copy_csv('file.csv')