How to add pandas data to an existing csv file?

后端 未结 6 1465
离开以前
离开以前 2020-11-22 10:02

I want to know if it is possible to use the pandas to_csv() function to add a dataframe to an existing csv file. The csv file has the same structure as the load

6条回答
  •  无人共我
    2020-11-22 10:20

    A bit late to the party but you can also use a context manager, if you're opening and closing your file multiple times, or logging data, statistics, etc.

    from contextlib import contextmanager
    import pandas as pd
    @contextmanager
    def open_file(path, mode):
         file_to=open(path,mode)
         yield file_to
         file_to.close()
    
    
    ##later
    saved_df=pd.DataFrame(data)
    with open_file('yourcsv.csv','r') as infile:
          saved_df.to_csv('yourcsv.csv',mode='a',header=False)`
    

提交回复
热议问题