Python: Can't convert 'list' object to str implicitly - python

I am trying to read a file called differences.txt and put it into a one line variable.
Here is differences.txt:
192.168.0.***
192.168.0.***
and my code:
with open ("/home/pi/Documents/difference.txt") as myfile:
difip=myfile.readlines()
print (difip)
and my error:
Traceback (most recent call last):
File "/home/pi/Desktop/clean.py", line 95, in <module>
body = "Different IP's:" + difip
TypeError: Can't convert 'list' object to str implicitly
Any help will be awesome! Thank you!

myfile.readlines()
returns a list of lines of the file
(remember, this includes \n for new lines). In your case it's returning
["192.168.0.***\n", "192.168.0.***\n"]
Optn 1) You should be using the strip() function instead
myfile = open('/home/pi/Documents/difference.txt', 'r')
text = myfile.read().strip() #pass ("\n") as argument to strip() to remove the newlines.
Optn 2) Optionally you can use your same code but modify the last line as follows:
with open ("/home/pi/Documents/difference.txt") as myfile:
difip=myfile.readlines()
print (difip[0] + difip[1])
This error message
TypeError: Can't convert 'list' object to str implicitly
is telling you that you are trying to print the list as a string. What this last change makes is print the strings that are stored in the first two lines of the text file.

Related

Python: returning 'None' from a sub and printing return value

I have the python script below which returns a variable which can either be None or a blob of data read from a file. I thought this would be an easy way to determine one of three states:
any error returns None
empty data returns an empty variable
successful read returns data in variable
This (also below) is the error I am getting. I could just assign "" to data instead of None and test for an empty variable but that seems a little cheesy. Printing the variable wrapped in str() might work but that seems like a lot of extra typing (or special function to print the variable) every time I want to print the variable. I must be waaayyy off base here.
$ ./foo.py
Traceback (most recent call last):
File "./foo.py", line 20, in <module>
print " data read was " + line_read
TypeError: cannot concatenate 'str' and 'builtin_function_or_method' objects
code:
#!/usr/bin/python
import sys, os
def get_data (src):
data = None
if os.path.isfile (src):
with open(src, 'rt') as f:
data = f.read
return data
line_read = get_data('foo.txt')
if line_read is None:
print "no data in file"
sys.exit(1)
print " data read was " + line_read
It seems the problem is you are using f.read. Python supports high-order programming, which in essence allows you to assign functions/method to variables. Then, what you are returning from get_data is basically a function which cannot be concatenated with a string which is the error you are getting, so to fix this call the method read as follows:
#!/usr/bin/python
import sys, os
def get_data (src):
data = None
if os.path.isfile (src):
with open(src, 'rt') as f:
data = f.read() # this will solve your problem
return data
line_read = get_data('foo.txt')
if line_read is None:
print "no data in file"
sys.exit(1)
print " data read was " + line_read
You have just assigned variable data to a method with that data = f.read call, you should actually call that method with:
data = f.read()
You should perhaps add parenthesis from wherever you are calling a function. In your program,f.read() is a function but you typed it as f.read which causes the error. The solution is to replace f.read with f.read().

How can I get a number from an XML file as an integer?

I have been trying to code something on Python recently that looks for a part of an XML file, and prints the result. Very simple, but I need some help with trying to get an integer from the XML.
XML:
<totalPages>2</totalPages>
Python:
xmldoc = minidom.parse('group.xml')
pagenum = xmldoc.getElementsByTagName('totalPages')
When trying to run that code along with the following code I get an error, which is also below:
if pagenum > 1:
...
Error:
Traceback (most recent call last):
File "app.py", line 13, in <module>
pagenum = int(xmldoc.getElementsByTagName('totalPages'))
TypeError: int() argument must be a string, a bytes-like object or a number, not 'NodeList'
Note that pagenum is a NodeList, so you have to get an item from the list, get a child (Element), and get its data. Using you example:
if int(pagenum.item(0).lastChild.data) > 1:

Creating a program to store all the tweets off a page to be stored in a text file for analysis, however getting TypeErrors

I have started off by including Tweepy and managed to get a program that is able to output a correct output with a search parameter, however, while trying to create a program that can save and store a person timeline for data analysis I came across a TypeError: must be str, not ResultSet.
import tweepy
#API keys access
auth = tweepy.OAuthHandler("", "")
auth.set_access_token("", "")
client = tweepy.API(auth)
#Opening a file with the name of the user wanted
screen = input("Enter the screen name: ")
filename = (screen+".txt")
file = open(filename, "w")
#Getting the Users time line
user = client.get_user(screen_name=screen)
timeline = user.timeline()
#Writing new found data to the file.
file.write(timeline)
file.close()
This code keeps on spitting out the error:
Traceback (most recent call last):
File "GetTimeLine.py", line 20, in <module>
file.write(timeline)
TypeError: must be str, not ResultSet
However for the set line:
file.write(timeline)
I add where I want it to become str through the user of
file.write(str(timeline))
Throwing out an entirely different error.
Traceback (most recent call last):
File "GetTimeLine.py", line 20, in <module>
file.write(str(timeline))
File "C:\Program Files (x86)\Python\lib\encodings\cp1252.py", line 19, in encode
return codecs.charmap_encode(input,self.errors,encoding_table)[0]
UnicodeEncodeError: 'charmap' codec can't encode characters in position 4122-4123: character maps to <undefined>
To try and fix this I tried to add .(encode"utf-8") however with no luck.
Any help greatly appreciated.
Try this, I searched for how to convert ResultSet to string and found this
unicode.join(u'\n',map(unicode,result))
Here "result" is your "timeline" variable, just put it and you will get it in string format. Doing simply str(timeline) will not encode it , that's why you are getting another error.
Just try it:) Cheers

when creating script have :TypeError: '_io.TextIOWrapper' object is not subscriptable

I am trying to make my code narrow down words in a listing an input then sorting them into a different list but it threw out this can anyone help me?
Traceback (most recent call last):
File "C:/Users/dan/Desktop/python/threeword.py", line 4, in <module>
word = words[x],words[(x+1)],words[(x+2)]
TypeError: '_io.TextIOWrapper' object is not subscriptable
words=open("three.txt",'r+')
f=open("three1","w")
for x in words:
word = words[x],words[(x+1)],words[(x+2)]
print(word)
input=('y or n')
if input=="y":
f.write(word)
x=x+3
elif input=='stop':
break
else:
x=x+3
f.close()
You problem is that you can't just flat out say words[0] when all you assigned words to is open(filename) the open function in python does not return a list(as you seem to think) instead is returns a file object as said in the python docs about what the open() function does:
Open a file, returning an object of the file type
instead do either
words = open(filename).read() or words = list(words) and then you can do words[0]

JSON Parsing Issue in python

When I'm trying to parse a JSON dump, I get this attribute error
Traceback (most recent call last):
File "Security_Header_Collector.py", line 120, in <module>
process(sys.argv[-1])
File "Security_Header_Collector.py", line 67, in process
server_details = json.load(header_final)
File "/usr/lib/python2.7/json/__init__.py", line 274, in load
return loads(fp.read(),
AttributeError: 'str' object has no attribute 'read'
Script:
finalJson[App[0]] = headerJson
header_final=json.dumps(finalJson,indent=4)
#print header_final
#json_data=open(header_final)
server_details = json.load(header_final)
with open("Out.txt",'wb') as f :
for appid, headers in server_details.iteritems():
htypes = [h for h in headers if h in (
'content-security-policy', 'x-frame-options',
'strict-transport-security', 'x-content-type-options',
'x-xss-protection')]
headers='{},{}'.format(appid, ','.join(htypes))
f.write(headers+'\n')
f.close()
json.dumps returns a JSON formatted string, but json.load expects to get file-like objects, not strings.
Solution: use json.loads instead of json.load in your code
Your code
header_final=json.dumps(finalJson,indent=4)
will give you string,
you have to use json.loads to convert string to json.
json.load - is used for files / objects
json.loads - is used for the strings or array elements.
You may also think about creating the whole JSON in the form of HEREDOC formate at once and latter apply escaping on it - this way it become easier to validate JSON format.

Categories

Resources