Attributeerror str object has no attribute read

In Python I'm getting an error:

Exception: (<type 'exceptions.AttributeError'>, AttributeError("'str' object has no attribute 'read'",), <traceback object at 0x1543ab8>)

Given python code:

def getEntries (self, sub): url = '//www.reddit.com/' if (sub != ''): url += 'r/' + sub request = urllib2.Request (url + '.json', None, {'User-Agent' : 'Reddit desktop client by /user/RobinJ1995/'}) response = urllib2.urlopen (request) jsonStr = response.read() return json.load(jsonStr)['data']['children']

What does this error mean and what did I do to cause it?

This question is tagged with python python-2.7 urllib2 attributeerror

~ Asked on 2012-06-24 00:12:14

~ Answered on 2012-06-24 00:33:50

If you get a python error like this:

AttributeError: 'str' object has no attribute 'some_method'

You probably poisoned your object accidentally by overwriting your object with a string.

How to reproduce this error in python with a few lines of code:

#!/usr/bin/env python import json def foobar(json): msg = json.loads(json) foobar('{"batman": "yes"}')

Run it, which prints:

AttributeError: 'str' object has no attribute 'loads'

But change the name of the variablename, and it works fine:

#!/usr/bin/env python import json def foobar(jsonstring): msg = json.loads(jsonstring) foobar('{"batman": "yes"}')

This error is caused when you tried to run a method within a string. String has a few methods, but not the one you are invoking. So stop trying to invoke a method which String does not define and start looking for where you poisoned your object.

~ Answered on 2014-10-29 19:51:44

Today we’ll look into a common error that you might get in your Python 3 development environment (such as Pycharm, Jupyter, VSCOde, IDLE etc’) when trying to insert text into a string using the append method. It’s key to understand that append is a method of the list object and not relevant to strings. Read on for how we can fix this error.

Using join to solve attribute error no append for strings

Assume you have the following couple of strings that you would like to concatenate

pack_str = "Pandas,Numpy,Seaborn,Matplotlib" new_elm = 'C++'

Let’s see what happens if we try to simply append a new element into the string:

pack_str.append(new_elm)

Here’s our error:

Fix the attributeerror: str object has no attribute append

A simple solution is to use the string join method instead:

', '.join([pack_str, new_elm])

This will render the following string:

'Pandas, Numpy, Seaborn, Matplotlib, C++'

How did that work? We passed a list containing all strings we would like to concatenate and defined comma as the separator.

Solve the attribute error by appending to a list

A little bit more busy method that you can use is to split your string into elements in a list, then use the append list method, and then converting the list to a string using join.

Here we go with the code snippet that you can use:

pack_str_lst = pack_str.split(',') pack_str_lst.append('C++') ', '.join(pack_str_lst)

And the resulting string object , as expected will be:

'Pandas, Numpy, Seaborn, Matplotlib, C++'

Troubleshooting the str has no attribute decode error

A somewhat related error when manipulating strings is that when you try to decode a string in Python3 you get the following error message:

pack_str = "Pandas,Numpy,Seaborn,Matplotlib" print(pack_str.decode('UTF-8'))

In Python 3 strings come encoded as unicode sequences therefore you are able to refer to the string directly without decoding it:

print(pack_str)

str object has no attribute read ,I'm parsing a string type to my stopword removing statement and I get this error 'str' object has no attribute 'read'. why?,73594/str-object-has-no-attribute-read,In the below section you are trying to pass string but sting has no attribute read. 

I'm parsing a string type to my stopword removing statement and I get this error 'str' object has no attribute 'read'. why?

def stopWordRemove(token_data): stopword = file_name ar_list = stopword.read().split('\n') needed_word = [] word = word_tokenize(token_data) for w in words: if w not in (ar_list): needed_word.append(w) filterd_sentence = ' '.join(needed_word) return filterd_sentence print(ar_list) print(stopWordRemove("احسن من ترحال"))

In the below section you are trying to pass string but sting has no attribute read. 

stopword = file_name ar_list = stopword.read().split('\n')

So if you are trying to read data from a file then you can use the open function as given below.

stopword = open('file_name', "r") ar_list = stopword.read().split('\n')


The Python "AttributeError: 'str' object has no attribute 'read'" occurs when we call the read() method on a string (e.g. a filename) instead of a file object or use the json.load() method by mistake. To solve the error, call the read() method on the file object after opening the file.,We tried to call the read() method on the filename string instead of the file object which caused the error.,Another common cause of the error is using the json.load() method when trying to parse a JSON string into a native Python object.,If you are reading from a file, make sure to call the read() method on the file object instead.

Copied!file_name = 'example.txt' with open(file_name, encoding = 'utf-8') as f: #⛔️ AttributeError: 'str' object has no attribute 'read' read_data = file_name.read() print(read_data)

Copied!file_name = 'example.txt' with open(file_name, encoding = 'utf-8') as f: #✅ calling read() on file object read_data = f.read() print(read_data)

Copied! import json #⛔️ AttributeError: 'str' object has no attribute 'read' result = json.load('{"name": "Alice"}')

Copied!import json result = json.loads('{"name": "Alice"}') print(type(result)) # 👉️ <class 'dict'> print(result) # 👉️ {'name': 'Alice'}

Copied! import json file_name = 'example.json' with open(file_name, 'r', encoding = 'utf-8') as f: my_data = json.load(f) print(my_data) #👉️ { 'name': 'Alice', 'age': 30 }


read closely, it is two different functions with very similar names.json.load() takes a file like object with a read() method, json.loads() takes a string.It 's easy to miss the "s" at the end and think they are the same method. – Joshmaker Apr 25 '13 at 12:02


Odoo's unique value proposition is to be at the same time very easy to use and fully integrated.

/

t - attf - class = "form-control o_website_form_input #{error.get('attachment_ids') and 'is-invalid' or ''} " id = "attachment_ids" name = "attachment_ids" t - att - value = "attachment_ids" multiple = "true" / >

'attachment_ids': base64.encodestring(kw.get("attachment_ids").read()),

Try by adding these attributes in the form 

enctype = "multipart/form-data" method = "post"

the way of assignment is wrong, Many2many do not take values like check the source code for example.

'attachment_ids': base64.encodestring(kw.get("attachment_ids").read())

3._

'attachment_ids': base64.encodestring(kw.get("attachment_ids").read())

'attachment_ids': base64.encodestring(kw.get("attachment_ids").read())


So if you encounter AttributeError: ‘str’ object has no attribute ‘decode’, it means that the string object is already in the Unicode format. You cannot apply the decode() method on an already decoded object.,The AttributeError: ‘str’ object has no attribute ‘decode’ occurs if you are using the decode() method on the string object, which is already in Unicode format. ,In Python 3, all the strings are in Unicode format by default. If you try to decode the Unicode string in Python 3, you will encounter an AttributeError: ‘str’ object has no attribute ‘decode’.,I am using the decode() method on the plain string object, which is already in decoded format. When I execute this code in Python 3, we encounter an AttributeError.

Example –

text = "ItsMyCode" print(text.decode())

Output

Traceback (most recent call last): File "c:\Code\main.py", line 2, in <module> print(text.decode()) AttributeError: 'str' object has no attribute 'decode'. Did you mean: 'encode'?

There is another trick where people apply encoding first and decoding again that is not recommended, and it would be redundant to perform this operation.

text = "ItsMyCode" print(text.encode().decode())


AttributeError(“‘str’ object has no attribute ‘read'”)

#!/usr/bin/env python import json def foobar(jsonstring): msg = json.loads(jsonstring) foobar('{"batman": "yes"}')

f = open('test.json') json_file = json.load(f)

import json from json import dumps strinjJson = '{"event_type": "affected_element_added"}' data = json.loads(strinjJson) print(data)


AttributeError: ‘str’ object has no attribute ‘read’,How to Solve Python AttributeError: ‘str’ object has no attribute ‘len’, Suf //researchdatapod.com/author/soofyserial/ How to Solve Python AttributeError: 'str' object has no attribute 'loads' ,The error occurs because the json.load() method expects a File object as a parameter but instead receives a string.

Let’s look at an example of using the read() method to read a file. The text file is ‘test.txt’ and has the following contents:

The code is as follows:

f = open('test.txt', 'r') print(type(f)) print(f.read())


How do I fix AttributeError str object has no attribute read?

The Python "AttributeError: 'str' object has no attribute 'read'" occurs when we call the read() method on a string (e.g. a filename) instead of a file object or use the json. load() method by mistake. To solve the error, call the read() method on the file object after opening the file.

What is JSON load?

load() json. load() takes a file object and returns the json object. It is used to read JSON encoded data from a file and convert it into a Python dictionary and deserialize a file itself i.e. it accepts a file object.

Related Posts

Toplist

Latest post

TAGs