我想从带有请求的链接下载csv文件,并将其另存为MSFT.csv
。
但是,我的代码返回错误
文件“< stdin>”,第1行,in _csv.Error:在未引用字段中看到的换行符 - 您是否需要以通用换行模式打开文件?
import requests
import csv
data=requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'
cr = csv.reader(data)
for row in cr:
print row
如何使用MSFT.csv
保存?
答案 0 :(得分:7)
如果您尝试将此数据写入CSV文件,可以先使用#include <sys/timerfd.h>
#include <sys/poll.h>
#include <sys/epoll.h>
#include <stdio.h>
#include <stdlib.h>
#include <strings.h>
#include <unistd.h>
int main(int ac, char *av[])
{
int timerfd;
int epollfd;
struct itimerspec timerValue;
uint64_t exp;
ssize_t s;
/* set timerfd */
timerfd = timerfd_create(CLOCK_MONOTONIC, 0);
if (timerfd < 0) {
printf("failed to create timer fd\n");
exit(1);
}
bzero(&timerValue, sizeof(timerValue));
timerValue.it_value.tv_sec = 1;
timerValue.it_value.tv_nsec = 0;
timerValue.it_interval.tv_sec = 1;
timerValue.it_interval.tv_nsec = 0;
/* start timer */
if (timerfd_settime(timerfd, 0, &timerValue, NULL) < 0) {
printf("could not start timer\n");
exit(1);
}
s = read( timerfd, &exp, sizeof(uint64_t));
exit(0);
}
下载。
requests.get
如果您使用的是import requests
data = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv')
,请将csv
内容传递给.text
并重复:
csv.reader
或者,使用pandas,将import csv
with open('out.csv', 'w') as f:
writer = csv.writer(f)
reader = csv.reader(data.text.splitlines())
for row in reader:
writer.writerow(row)
发送到缓冲区并将其传递给data.text
。
pd.read_csv
答案 1 :(得分:4)
您可以通过
请求来实现import os
import requests
def download_file(url, filename):
''' Downloads file from the url and save it as filename '''
# check if file already exists
if not os.path.isfile(filename):
print('Downloading File')
response = requests.get(url)
# Check if the response is ok (200)
if response.status_code == 200:
# Open file and write the content
with open(filename, 'wb') as file:
# A chunk of 128 bytes
for chunk in response:
file.write(chunk)
else:
print('File exists')
您可以使用所需的网址和文件名调用该函数。在你的情况下,它将是:
url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'
filename = 'MSFT.csv'
download_file(url, filename)
希望这有帮助。
答案 2 :(得分:0)
为您提供一种更简单的方法。
import urllib.request
csv_url = 'https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv'
urllib.request.urlretrieve(csv_url, 'MSFT.csv')
答案 3 :(得分:-1)
你去吧
import requests, csv
download = requests.get('https://www.alphavantage.co/query?function=TIME_SERIES_DAILY_ADJUSTED&symbol=MSFT&apikey=demo&datatype=csv')
with open('MSFT.csv', 'w') as temp_file:
temp_file.writelines(download.content)