TypeError: a bytes-like object is required, not 'str' in python and CSV
You are using Python 2 methodology instead of Python 3.
Change:
outfile=open('./immates.csv','wb')
To:
outfile=open('./immates.csv','w')
and you will get a file with the following output:
SNo,States,Dist,Population
1,Andhra Pradesh,13,49378776
2,Arunachal Pradesh,16,1382611
3,Assam,27,31169272
4,Bihar,38,103804637
5,Chhattisgarh,19,25540196
6,Goa,2,1457723
7,Gujarat,26,60383628
.....
In Python 3 csv takes the input in text mode, whereas in Python 2 it took it in binary mode.
Edited to Add
Here is the code I ran:
url='http://www.mapsofindia.com/districts-india/'
html = urllib.request.urlopen(url).read()
soup = BeautifulSoup(html)
table=soup.find('table', attrs={'class':'tableizer-table'})
list_of_rows=[]
for row in table.findAll('tr')[1:]:
list_of_cells=[]
for cell in row.findAll('td'):
list_of_cells.append(cell.text)
list_of_rows.append(list_of_cells)
outfile = open('./immates.csv','w')
writer=csv.writer(outfile)
writer.writerow(['SNo', 'States', 'Dist', 'Population'])
writer.writerows(list_of_rows)
TypeError: a bytes-like object is required, not 'str' when trying to write in csv file
The csv
module is one of the pieces where the conversion Python2 -> Python3 is not really straightforward. The underlying file is expected to be opened as text and no longer as a binary file, but with empty end of lines.
So I would write:
with open('C:/path_to_csv_file/fold1_1.csv', 'w', newline='', encoding='utf-8') as csvfile:
spamwriter = csv.writer(csvfile, delimiter=',', quotechar='|', quoting=csv.QUOTE_MINIMAL)
for row, timeseq in izip(fold1, fold1_t):
spamwriter.writerow([s +'#{}'.format(t) for s, t in izip(row, timeseq)])
The current error is caused by the csv module sending a unicode string while the undelying file expected bytes.
TypeError: a bytes-like object is required, not 'str' Using BytesIO
The error basically says your string is byte string. To solve this, I think you can try to use .decode('utf-8')
url = urlopen(address)
zipfile = ZipFile(BytesIO(url.read()))
return [tldextract.extract(x.split(',')[1]).domain for x in \
zipfile.read(filename).decode('utf-8').split()[:num]]
Error: bytes-like object is required, not 'str' on pd.read_csv
rawData
isn't a bytes
object. check_output
returns one, but you immediately decoded it into a str
object:
rawData = subprocess.check_output(...).decode('utf-8')
Just omit that method call.
Python requests. TypeError: a bytes-like object is required
Send the data in the body for the post call.
You can refer to the examples in the documentation: https://documentation.mailgun.com/en/latest/quickstart-sending.html#send-via-api
Note: switch over to python (required) language tab in the documentation.
Example from above docs:
def send_simple_message():
payload = {"from": "Excited User <mailgun@YOUR_DOMAIN_NAME>",
"to": ["bar@example.com", "YOU@YOUR_DOMAIN_NAME"],
"subject": "Hello",
"text": "Testing some Mailgun awesomness!"}
return requests.post( "https://api.mailgun.net/v3/YOUR_DOMAIN_NAME/messages",
auth=("api", "YOUR_API_KEY"),
data=payload)
TypeError: a bytes-like object is required, not 'str' when writing to a file in Python 3
You opened the file in binary mode:
with open(fname, 'rb') as f:
This means that all data read from the file is returned as bytes
objects, not str
. You cannot then use a string in a containment test:
if 'some-pattern' in tmp: continue
You'd have to use a bytes
object to test against tmp
instead:
if b'some-pattern' in tmp: continue
or open the file as a textfile instead by replacing the 'rb'
mode with 'r'
.
Related Topics
How to Get Rid of "Unnamed: 0" Column in a Pandas Dataframe Read in from CSV File
How to Remove Nan Values from a Numpy Array
How to See If There's an Available and Active Network Connection in Python
Read File from Line 2 or Skip Header Row
Making the Background Move Sideways in Pygame
Using Django Time/Date Widgets in Custom Form
Convert Unix Time to Readable Date in Pandas Dataframe
How to Validate a Url in Python? (Malformed or Not)
How to Find All Positions of the Maximum Value in a List
Why Does Assigning to My Global Variables Not Work in Python
Get the Second Largest Number in a List in Linear Time
Subprocess.Call Using String VS Using List
Isprime Function for Python Language
How to Expand a List to Function Arguments in Python
Python Unexpected Eof While Parsing
Get the Key Corresponding to the Minimum Value Within a Dictionary
How to Create Test and Train Samples from One Dataframe with Pandas