简体   繁体   中英

having problems downloading a csv file

So I was trying to make a function that downloads a csv file using the csv download link and then basically prints it dividing it in lines but I'm having problems when I have to save

def download_data(csv_url):
    response = request.urlopen(csv_url)
    csv = response.read()
    csv_str = str(csv)
    lines = csv_str.split("\\n")
    dest_url = r'data.csv'
    fx = open(dest_url, 'r')
    for line in lines:
      fx.write(line + '/n')
    fx.close()

when I give it the csv link , it tells me it can't find file/directory "data.csv" even though I should've downloaded it. Running Mac os

You're reading the file. Change the 'r' in fx = open(dest_url, 'r') to 'w' .

fx = open(dest_url, 'w')

As a side note you really should be using a with statement . with will make the file object close the connection once the code leaves the the with 's scope. This way you don't have to worry about closing the connection.

def download_data(csv_url):
    response = request.urlopen(csv_url)
    with open('data.csv', 'w') as f:
        f.write(str(response.read()))

Though really there isn't any need to save the file at all if you're just going to read it and display the contents on the screen. Just have download_data return csv_str .

Finally take a look at the builtin csv module . It makes life easy.

import csv
from io import StringIO
import requests


def download_data(csv_url):
    return csv.reader(
        StringIO(
            requests.get(csv_url)
                    .text
        ), delimiter=','
    )

for row in download_data('https://people.sc.fsu.edu/~jburkardt/data/csv/addresses.csv'):
    print("| {} |".format(str(' | '.join(row))))

# Prints:
#
# | John | Doe | 120 jefferson st. | Riverside |  NJ |  08075 |
# | Jack | McGinnis | 220 hobo Av. | Phila |  PA | 09119 |
# | John "Da Man" | Repici | 120 Jefferson St. | Riverside |  NJ | 08075 |
# | Stephen | Tyler | 7452 Terrace "At the Plaza" road | SomeTown | SD |  91234 |
# |  | Blankman |  | SomeTown |  SD |  00298 |
# | Joan "the bone", Anne | Jet | 9th, at Terrace plc | Desert City | CO | 00123 |

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM