且构网

分享程序员开发的那些事...
且构网 - 分享程序员编程开发的那些事

删除csv文件中的特定行从Python 3.4.3

更新时间:2023-12-03 21:35:04

你可以这样做,首先下载并保存webdata到一个临时文件,然后复制到最终目标文件,但跳过前面的17行。

You could do it like this which first downloads and saves the webdata into a temporary file, and then copies it to the final destination file but skips the first 17 rows at the beginning.

import csv
import os
import urllib.request, urllib.parse, urllib.error

ASXCode = 'CSL'
local_filename = "Intra_" + ASXCode + ".csv"
url = ('http://chartapi.finance.yahoo.com/instrument/1.0/' + ASXCode +
       '.ax/chartdata;type=quote;range=1d/csv')

temp_filename, headers = urllib.request.urlretrieve(url)

with open(temp_filename, 'r', newline='') as inf, \
     open(local_filename, 'w', newline='') as outf:
    reader = csv.reader(inf)
    writer = csv.writer(outf)
    for _ in range(17):   # skip first 17 rows
        next(reader)
    writer.writerows(reader)  # copy the rest

os.remove(temp_filename)  # clean up
print('{} downloaded'.format(local_filename))