Python Forum
CSV file from Binary to String
Thread Rating:
  • 0 Vote(s) - 0 Average
  • 1
  • 2
  • 3
  • 4
  • 5
CSV file from Binary to String
#3
Quote:_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
urlopen() always return bytes and csv reader need string.
Then it's to late to decode on row.
import urllib.request
import csv

url = 'adress'
site = urllib.request.urlopen(url)
with open(site.read().decode('utf-8')) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
Use always Requests then do not need to guess on encoding as get correct encoding from site.
import requests

url = 'adress'
site = requests.get(url)
with open(site.text) as csvfile:
    reader = csv.DictReader(csvfile)
    for row in reader:
        print(row)
It's usually utf-8,but csv files can have other encoding.
>>> import requests
>>> 
>>> url = 'https://www.stats.govt.nz/....bands-csv.csv'
>>> site = requests.get(url)
>>> site.encoding
'ISO-8859-1' 
Also one of the simplest way out there is to use Pandas.
import pandas as pd

data = pd.read_csv('https://some.csv')
Reply


Messages In This Thread
CSV file from Binary to String - by mr_byte31 - Jul-26-2019, 08:55 AM
RE: CSV file from Binary to String - by micseydel - Jul-27-2019, 06:23 PM
RE: CSV file from Binary to String - by snippsat - Jul-27-2019, 08:46 PM

Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 951 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  How do I read and write a binary file in Python? blackears 6 8,594 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Add one to binary string uwl 2 1,122 Sep-11-2022, 05:36 PM
Last Post: uwl
  Hashing an address for binary file Python_help 8 2,896 Nov-04-2021, 06:23 AM
Last Post: ndc85430
  Read/Write binary file deanhystad 3 3,417 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  [HELP] string into binary ZeroPy 2 2,189 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  Binary File Error SalsaBeanDip 1 1,865 Oct-12-2020, 09:13 PM
Last Post: bowlofred
  Convert file of hex strings to binary file medatib531 4 14,190 Oct-09-2020, 05:42 PM
Last Post: DeaD_EyE
  Binary File Read Aussie 6 8,918 Sep-03-2020, 03:57 AM
Last Post: deanhystad
  Binary file Aussie 12 4,890 Aug-31-2020, 09:20 PM
Last Post: Aussie

Forum Jump:

User Panel Messages

Announcements
Announcement #1 8/1/2020
Announcement #2 8/2/2020
Announcement #3 8/6/2020