简体   繁体   中英

appending data to a CSV file and removing list brackets?

I built a web scraping class and am now trying to write the average costs & other values to a csv file with this method--

def avg_data_to_csv(self):
    avg_data = self.avg_data
    df = pd.DataFrame(avg_data, columns=['Location', 'Average Price', 'Average Price per SQFT'])
    csv = df.to_csv('AVG_DATA.csv', index=False)
    return csv

I then wrote another method to add the updated average values to the same csv file in a new row each time I run the program--

def add_to_avg_csv(self):
    new_data = self.avg_data
    with open('AVG_DATA.csv', 'a') as obj:
        writer_object = csv.DictWriter(obj, fieldnames=self.avg_data)
        writer_object.writerow(new_data)
        obj.close()

However, when I test this, my csv file looks like this-

csv file after two runs

I can't figure out how to add the data without the list brackets. How would I go about removing the list brackets when I add the new data to the file?

Since you are using writerow() the easiest way would be for your function avg_data_to_csv() to return a string of your new data record instead of a one row dataframe.

Another way would be to open 'AVG_DATA.csv' with pandas, concat/append the output of avg_data_to_csv(), and then save it as 'AVG_DATA.csv'.

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM