简体   繁体   English

将数据附加到 CSV 文件并删除列表括号?

[英]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--我构建了一个网络抓取类,现在正尝试使用这种方法将平均成本和其他值写入 csv 文件——

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--然后我编写了另一种方法,每次运行程序时将更新的平均值添加到新行中的同一个 csv 文件中——

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 文件如下所示 -

csv file after two runs两次运行后的 csv 文件

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.由于您使用的是 writerow() 最简单的方法是让函数 avg_data_to_csv() 返回新数据记录的字符串而不是单行数据帧。

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'.另一种方法是用 pandas 打开“AVG_DATA.csv”,连接/附加 avg_data_to_csv() 的输出,然后将其保存为“AVG_DATA.csv”。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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