Python 将CSV的最后13行复制到新的CSV
我的代码将13家公司的最新股票信息附加到csv文件中(更新的股票报价)。引号将添加到文件的底部。我只想将最近的报价(13行)复制到一个新的csv文件中,该文件一次只包含每个股票的最新报价。这将允许我仅将最新的引号导入excel文件。有什么想法吗Python 将CSV的最后13行复制到新的CSV,python,csv,Python,Csv,我的代码将13家公司的最新股票信息附加到csv文件中(更新的股票报价)。引号将添加到文件的底部。我只想将最近的报价(13行)复制到一个新的csv文件中,该文件一次只包含每个股票的最新报价。这将允许我仅将最新的引号导入excel文件。有什么想法吗 import urllib.request from bs4 import BeautifulSoup import csv from datetime import datetime from urllib.request import Request
import urllib.request
from bs4 import BeautifulSoup
import csv
from datetime import datetime
from urllib.request import Request, urlopen
from twilio.rest import Client
import os
import random
# list yahoo finance urls for desired stocks
yahoo_urls = ['https://finance.yahoo.com/quote/%5EDJI?p=^DJI', 'https://finance.yahoo.com/quote/%5ESPX?p=^SPX', 'https://finance.yahoo.com/quote/AAPL?p=AAPL', 'https://finance.yahoo.com/quote/KO/', 'https://finance.yahoo.com/quote/SBUX?p=SBUX', 'https://finance.yahoo.com/quote/DIS?p=DIS', 'https://finance.yahoo.com/quote/BRK-B?p=BRK-B', 'https://finance.yahoo.com/quote/NKE?p=NKE']
# loop for each stock with user-agent
for url in yahoo_urls:
full_access = Request(url, headers={'User-Agent': 'Mozilla/5.0 (Windows; U; Windows NT 6.1; en-US) AppleWebKit/534.20 (KHTML, like Gecko) Chrome/11.0.672.2 Safari/534.20'})
# query the website and return the html to the variable ‘page’
page = urllib.request.urlopen(full_access)
# parse the html using beautiful soup and store in variable `soup`
soup = BeautifulSoup(page, "html.parser")
# Take out the <div> of name and get its value
name_box = soup.find("h1", "D(ib) Fz(18px)")
name = name_box.text.strip()
print(name)
#get the index price
price_box = soup.find("span", "Trsdu(0.3s) Fw(b) Fz(36px) Mb(-4px) D(ib)")
price = price_box.text.strip()
print(price)
# #Day Change
try:
change_box = soup.find("span", class_="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataGreen)")
change = change_box.text.strip()
print(change)
except AttributeError:
change_box = soup.find("span", class_="Trsdu(0.3s) Fw(500) Pstart(10px) Fz(24px) C($dataRed)")
change = change_box.text.strip()
print(change)
# # open a csv file with append, so old data will not be erased
with open("updated_quotes", "a") as csv_file:
writer = csv.writer(csv_file)
writer.writerow([name, price, change, datetime.now()])
导入urllib.request
从bs4导入BeautifulSoup
导入csv
从日期时间导入日期时间
从urllib.request导入请求,urlopen
从twilio.rest导入客户端
导入操作系统
随机输入
#列出所需股票的yahoo finance URL
雅虎网址=['https://finance.yahoo.com/quote/%5EDJI?p=^DJI','https://finance.yahoo.com/quote/%5ESPX?p=^SPX','https://finance.yahoo.com/quote/AAPL?p=AAPL', 'https://finance.yahoo.com/quote/KO/', 'https://finance.yahoo.com/quote/SBUX?p=SBUX', 'https://finance.yahoo.com/quote/DIS?p=DIS', 'https://finance.yahoo.com/quote/BRK-B?p=BRK-B','https://finance.yahoo.com/quote/NKE?p=NKE']
#使用用户代理为每个股票循环
对于yahoo_url中的url:
完整访问=请求(url,标题={'User-Agent':'Mozilla/5.0(Windows;U;Windows NT 6.1;en-US)AppleWebKit/534.20(KHTML,像Gecko)Chrome/11.0.672.2 Safari/534.20')
#查询网站并将html返回到变量“page”
page=urllib.request.urlopen(完全访问)
#使用Beauty soup解析html并存储在变量'soup'中`
soup=BeautifulSoup(第页,“html.parser”)
#取出of name并获取其值
name_box=soup.find(“h1”,“D(ib)Fz(18px)”)
name=name\u box.text.strip()
印刷品(名称)
#获取指数价格
price_box=soup.find(“span”,“Trsdu(0.3s)Fw(b)Fz(36px)Mb(-4px)D(ib)”)
price=price\u box.text.strip()
印刷品(价格)
##换日
尝试:
change_box=soup.find(“span”,class_uu=“Trsdu(0.3s)Fw(500)Pstart(10px)Fz(24px)C($dataGreen)”)
change=change\u box.text.strip()
打印(更改)
除属性错误外:
change_box=soup.find(“span”,class_uu=“Trsdu(0.3s)Fw(500)Pstart(10px)Fz(24px)C($dataRed)”)
change=change\u box.text.strip()
打印(更改)
##使用append打开csv文件,以便旧数据不会被擦除
打开(“更新的_引号”,“a”)作为csv_文件:
writer=csv.writer(csv\u文件)
writer.writerow([name,price,change,datetime.now()]))
一个糟糕的解决方案是只使用tail-n13 updated\u quotes.csv>last\u quotes.csv
。您可以通过子流程调用它。检查输出(“tail-n13 updated\u quotes.csv>last\u quotes.csv”,shell=True)
您可以在csv阅读器对象上使用deque
tail配方
如果您有一个标题,请保留该标题。然后在此处使用复制的标题:
def tail(filename, n=10):
'Return the last n lines of a file'
return deque(open(filename), n)
在interator(如文件或csv读取器或任何其他形式的Python迭代器)上调用deque
相当于在同一对象上调用list(迭代器)
。但是使用deque
可以限制大小并在该迭代器上创建Unix的tail
实用程序的等价物
下面是一个使用大范围对象并仅保留最后5个对象的示例:
>>> from collections import deque
>>> deque(range(100000),5)
deque([99995, 99996, 99997, 99998, 99999], maxlen=5)
我应该如何将最后n行写入新的csv文件?如果您可以创建某种形式的迭代器来读取所有相关数据(如
soup
)你可以通过deque
运行迭代器,并在for循环中使用该结果,或者将其作为csv.writer
的输入,就像你要编写所有这些一样。嗯。好的,我昨天刚开始学习编程,所以我必须做一些研究来找出如何做到这一点。别忘了关闭文件