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
#1
I try to open a CSV file from internet.
Then I try to parse it with CSV lib.
I get error that I deal with it in Binary.
any help?

with urllib.request.urlopen(url) as csvfile:
            reader = csv.DictReader(csvfile)
            for row in reader:
                print(row.decode('utf-8'))
Output:
_csv.Error: iterator should return strings, not bytes (did you open the file in text mode?)
Reply
#2
If I were in your situation, I'd either read the CSV string into memory and work with it from there, or if it's too big, then download it to disk and use a context manager on that created file.
Reply
#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


Possibly Related Threads…
Thread Author Replies Views Last Post
  Need to replace a string with a file (HTML file) tester_V 1 762 Aug-30-2023, 03:42 AM
Last Post: Larz60+
  How do I read and write a binary file in Python? blackears 6 6,513 Jun-06-2023, 06:37 PM
Last Post: rajeshgk
  Add one to binary string uwl 2 949 Sep-11-2022, 05:36 PM
Last Post: uwl
  Hashing an address for binary file Python_help 8 2,627 Nov-04-2021, 06:23 AM
Last Post: ndc85430
  Read/Write binary file deanhystad 3 3,180 Feb-01-2021, 10:29 AM
Last Post: Larz60+
  [HELP] string into binary ZeroPy 2 2,060 Dec-31-2020, 08:15 PM
Last Post: deanhystad
  Binary File Error SalsaBeanDip 1 1,756 Oct-12-2020, 09:13 PM
Last Post: bowlofred
  Convert file of hex strings to binary file medatib531 4 13,722 Oct-09-2020, 05:42 PM
Last Post: DeaD_EyE
  Binary File Read Aussie 6 8,370 Sep-03-2020, 03:57 AM
Last Post: deanhystad
  Binary file Aussie 12 4,490 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