删除csv文件中的特定行从Python 3.4.3 [英] Delete specific rows in csv file from Python 3.4.3

查看:530
本文介绍了删除csv文件中的特定行从Python 3.4.3的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我写的是我的第一个Python文件,它基本上抓取一些webdata并保存到一个.csv文件(和工作,见下文)。

I'm writing my first Python file which basically grabs some webdata and saves to a .csv file (and working, see below).

数据结构一致但具有由17行组成的标题。我想导入csv到SQL,但它有头部数据的麻烦,即使我告诉它开始从行18等读取,它不能看到数据,除非我手动删除行1-17。

The data structure is consistent but has a header consisting of some 17 rows. I want to import the csv into SQL, but its having trouble with the header data, even if I tell it to start reading from row 18 etc it can't see the data unless I manually delete rows 1-17.

我认为最简单的选择是简单地删除行1-17作为我下面的Python代码的一部分。但我不知道从哪里开始,所以任何提示赞赏。

I'm thinking the easiest option would be to simply delete rows 1-17 as part of my Python code below. But I have no idea where to start so any tips appreciated.

import urllib.request, urllib.parse, urllib.error

ASXCode = 'CSL'

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


推荐答案

你可以这样做,首先下载并保存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))

这篇关于删除csv文件中的特定行从Python 3.4.3的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆