1

每个人!我正在尝试从网站上抓取数据并将任何尚未复制到 .csv 文件的条目附加到 .csv 文件中,但我似乎无法让它正确写入。

url = 'www.website.com'

def getInfo():
    global oldMaxValue, oldMaxRow, newInfo
    newInfo = 0
    with open("file.csv", "a") as f:
        data = requests.get(url)
        text = data.text

        newRows = [line.split(',') for line in text.split("\n") if line]
        newMaxValue = max(row[0] for row in newRows)

        for i in newRows:
            if int(i[0]) > int(oldMaxValue):
                f.write(str(i))

        oldMaxValue = newMaxValue

任何指导将不胜感激。非常感谢!:)

4

1 回答 1

1

使用 csv 模块。这是将单行附加到现有文件的示例:

import csv

f = file("file.csv", 'a')
csv_writer = csv.writer(f)

my_record = ["This", "is", "a", "row", "of", "data"]

csv_writer.writerow(my_record)
于 2013-07-06T03:22:16.857 回答