python 3 unable to write to file - python

My code is:
from random import randrange, choice
from string import ascii_lowercase as lc
from sys import maxsize
from time import ctime
tlds = ('com', 'edu', 'net', 'org', 'gov')
for i in range(randrange(5, 11)):
dtint = randrange(maxsize)
dtstr = ctime()
llen = randrange(4, 8)
login = ''.join(choice(lc)for j in range(llen))
dlen = randrange(llen, 13)
dom = ''.join(choice(lc) for j in range(dlen))
print('%s::%s#%s.%s::%d-%d-%d' % (dtstr, login,dom, choice(tlds),
dtint, llen, dlen), file='redata.txt')
I want to print the results in a text file but I get this error:
dtint, llen, dlen), file='redata.txt')
AttributeError: 'str' object has no attribute 'write'

file should be a file object, not a file name. File objects have write method, str objects don't.
From the doc on print:
The file argument must be an object with a write(string) method; if it
is not present or None, sys.stdout will be used.
Also note that the file should be open for writing:
with open('redata.txt', 'w') as redata: # note that it will overwrite old content
for i in range(randrange(5,11)):
...
print('...', file=redata)
See more about the open function here.

Related

How to save <class "ctypes.c_char_Array> with pickle

I'm doing research on palmprint recognition. for that I use the edcc library for the introduction of the palmprint. but i have problem in saving the encoding result from palm. I want to save the encoding result into a file, but I get an error like below
Traceback (most recent call last):
File "/home/pi/Coba/PalmDetection/PalmRecognition.py", line 18, in <module>
pickle.dump(one_palmprint_code, config_dictionary_file)
_pickle.PicklingError: Can't pickle <class 'ctypes.c_char_Array_849'>: attribute lookup c_char_Array_849 on ctypes failed
My code like this :
import os
import edcc
import cv2
import pickle
TEST_PALMPRINT_DATA_DIR = "/home/pi/Coba/PalmDetection/Data"
TEST_A_01_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "Palm1.jpeg")
#TEST_A_02_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "a_02.bmp")
TEST_B_01_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "palme.jpeg")
#TEST_B_02_PALMPRINT_IMAGE = os.path.join(TEST_PALMPRINT_DATA_DIR, "b_02.bmp")
if __name__ == "__main__":
config = edcc.EncoderConfig(29, 5, 5, 10)
encoder = edcc.create_encoder(config)
one_palmprint_code = encoder.encode_using_file(TEST_A_01_PALMPRINT_IMAGE)
with open('encode.encode', 'wb') as config_dictionary_file:
pickle.dump(one_palmprint_code, config_dictionary_file)
another_palmprint_code = encoder.encode_using_file(TEST_B_01_PALMPRINT_IMAGE)
similarity_score = one_palmprint_code.compare_to(another_palmprint_code)
print(
"{} <-> {} similarity score:{}".format(
TEST_A_01_PALMPRINT_IMAGE, TEST_B_01_PALMPRINT_IMAGE, similarity_score
)
)
What should i do?
The edcc module must use ctypes internally, but really should hide that fact instead of returning a ctypes-wrapped object. A ctypes.c_char_Array_849 is just a C-compatible wrapper around an array of bytes. You can access the equivalent Python bytes object via the .raw property (what edcc should return instead) and write that to the file:
import ctypes
import pickle
one_palmprint_code = (ctypes.c_char * 849)()
with open('encode.encode', 'wb') as config_dictionary_file:
#pickle.dump(one_palmprint_code, config_dictionary_file) # reproduces error
config_dictionary_file.write(one_palmprint_code.raw)

TypeError: Can't convert 'bytes' object to str implicitly in python?

I was trying out Twitter API but it give me this error:
Traceback (most recent call last):
File "D:/MAGIC/python/twitterdemo.pu.py", line 23, in
text += status.text.encode('utf-8')
TypeError: Can't convert 'bytes' object to str implicitly
Here is my code:
import sys
import operator
import requests
import json
import twitter
from watson_developer_cloud import PersonalityInsightsV2 as PersonalityInsights
twitter_consumer_key = ''
twitter_consumer_secret = ''
twitter_access_token = ''
twitter_access_secret = ''
twitter_api = twitter.Api(consumer_key=twitter_consumer_key, consumer_secret=twitter_consumer_secret, access_token_key=twitter_access_token, access_token_secret=twitter_access_secret)
handle = "#somethingsoemthing"
statuses = twitter_api.GetUserTimeline(screen_name=handle, count=200, include_rts=False)
text = ""
for status in statuses:
print (status.text)
if(status.lang == 'en'): #Enligh tweets
text += status.text.encode('utf-8')
What am I doing wrong?
Your text is initialized as a str, and you're trying to add a bytes object (which is what status.text.encode('utf-8') returns) to it. Initialize text as a bytes object and that error should go away:
text = b''
Alternatively, you could skip encoding the text altogether and it should work:
text += status.text

decode binary from xmlrpc python

I'm new to python and xml-rpc , and I'm stuck with decoding binary data coming from a public service :
the service request response with this code is :
from xmlrpc.client import Server
import xmlrpc.client
from pprint import pprint
DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxxxxxx'
logFile = open('stat.txt', 'w')
s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')
token = s1.autenticazione.Accedi(DEV_KEY, '')
res = s2.paline.GetStatPassaggi(token)
pprint(res, logFile)
response :
{'id_richiesta': '257a369dbf46e41ba275f8c821c7e1e0',
'risposta': {'periodi_aggregazione': <xmlrpc.client.Binary object at 0x0000027B7D6E2588>,
'tempi_attesa_percorsi': <xmlrpc.client.Binary object at 0x0000027B7D9276D8>}}
I need to decode these two binary objects , and I'm stuck with this code :
from xmlrpc.client import Server
import xmlrpc.client
from pprint import pprint
DEV_KEY = 'xxxxxxxxxxxxxxxxxxxxxxxx'
logFile = open('stat.txt', 'w')
s1 = Server('http://muovi.roma.it/ws/xml/autenticazione/1')
s2 = Server('http://muovi.roma.it/ws/xml/paline/7')
token = s1.autenticazione.Accedi(DEV_KEY, '')
res = s2.paline.GetStatPassaggi(token)
dat = xmlrpc.client.Binary(res)
out = xmlrpc.client.Binary.decode(dat)
pprint(out, logFile)
that ends in :
Traceback (most recent call last): File "stat.py", line 18, in
dat = xmlrpc.client.Binary(res) File "C:\Users\Leonardo\AppData\Local\Programs\Python\Python35\lib\xmlrpc\client.py",
line 389, in init
data.class.name) TypeError: expected bytes or bytearray, not dict
The only doc I found for xmlrpc.client is the one at docs.python.org , but I can't figure out how I could decode these binaries
If the content of res variable (what you get from the 2nd (s2) server) is the response you pasted into the question, then you should modify the last 3 lines of your 2nd snippet to (as you already have 2 Binary objects in the res dictionary):
# ... Existing code
res = s2.paline.GetStatPassaggi(token)
answer = res.get("risposta", dict())
aggregation_periods = answer.get("periodi_aggregazione", xmlrpc.client.Binary())
timeout_paths = answer.get("tempi_attesa_percorsi", xmlrpc.client.Binary())
print(aggregation_periods.data)
print(timeout_paths.data)
Notes:
According to [Python.Docs]: xmlrpc.client - Binary Objects (emphasis is mine):
Binary objects have the following methods, supported mainly for internal use by the marshalling/unmarshalling code:
I wasn't able to connect (and this test the solution), since DEV_KEY is (obviously) fake

Python 3.5 BytesIO error

I am making a project all in python 2.7 but it started to give some errors to me on the final parts since the documentation is in python 3.5. So i am changing everything to python 3.5, but it is giving me a error because of bytesIO. Can you help me to understand why, and what should i do? The error is coming from def repr on string_dinamica.write('P3\n'). I left all the code in case that it´s needed. Thanks for the help. NOTE: Just to confirm this works on python 2.7 but not in 3.5
from io import BytesIO
from cor_rgb_42347 import CorRGB
class Imagem:
def __init__(self, numero_linhas, numero_colunas):
self.numero_linhas = numero_linhas
self.numero_colunas = numero_colunas
self.linhas = []
for n in range(numero_linhas):
linha = []
for m in range(numero_colunas):
linha.append(CorRGB(0.0, 0.0, 0.0))
self.linhas.append(linha)
def __repr__(self):
string_dinamica = BytesIO()
string_dinamica.write('P3\n')
string_dinamica.write("#mcg#leim#isel 2015/16\n")
string_dinamica.write(str(self.numero_colunas) + " " \
+ str(self.numero_linhas) + "\n")
string_dinamica.write("255\n")
for linha in range(self.numero_linhas):
for coluna in range(self.numero_colunas):
string_dinamica.write(str(self.linhas[linha][coluna])+ " ")
string_dinamica.write("\n")
resultado = string_dinamica.getvalue()
string_dinamica.close()
return resultado
def set_cor(self, linha, coluna, cor_rgb):
"""Permite especificar a cor RGB do pixel na linha "linha",
coluna "coluna".
"""
self.linhas[linha-1][coluna-1] = cor_rgb
def get_cor(self, linha, coluna):
"""Permite obter a cor RGB do pixel na linha "linha",
coluna "coluna".
"""
return self.linhas[linha-1][coluna-1]
def guardar_como_ppm(self, nome_ficheiro):
"""Permite guardar a imagem em formato PPM ASCII num ficheiro.
"""
ficheiro = open(nome_ficheiro, 'w')
ficheiro.write(str(self))
ficheiro.close()
if __name__ == "__main__":
imagem1 = Imagem(5,5)
print(imagem1)
Traceback (most recent call last):
File "C:\Users\Utilizador\Desktop\Projectos Finais\Projecto_42347\imagem_42347.py", line 60, in <module>
print(imagem1)
File "C:\Users\Utilizador\Desktop\Projectos Finais\Projecto_42347\imagem_42347.py", line 19, in __repr__
string_dinamica.write('P3\n')
TypeError: a bytes-like object is required, not 'str'
For Python 3, just change BytesIO to StringIO. Python 3 strings are Unicode strings instead of byte strings, and __repr__ should return a Unicode string in Python 3.
If you try to return a bytes object like some other answers suggest, you will get:
TypeError: __repr__ returned non-string (type bytes)
As I mentioned on my comment, BytesIO requires byte-like object.
Demo:
>>> from io import BytesIO
>>>
>>> b = BytesIO()
>>>
>>> b.write('TEST\n')
Traceback (most recent call last):
File "<pyshell#97>", line 1, in <module>
b.write('TEST\n')
TypeError: 'str' does not support the buffer interface
>>>
>>>
>>> b.write(b'TEST\n')
5
>>> v = b.getbuffer()
>>>
>>> v[2:4]=b'56'
>>>
>>> b.getvalue()
b'TE56\n'
So add to the beginning of your the param. in you pass to write method, b(for binary).

Variable not the same type in two different functions

I have two functions which print into an excel file. THe only input is the file name. Here is the code:
#excelpy
import excelpy
#Tinker
from Tkinter import *
from tkSimpleDialog import *
from tkFileDialog import *
Function Mode1
def Mode1(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST1', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m1 = testwbook.save(full_name)
testwbook.close()
return m1
Function Mode2
def Mode2(full_name):
print full_name
print type(full_name)
testwbook = excelpy.workbook(full_name)
testwbook.show()
testwbook.set_cell((1,1),'TEST2', fontColor='red')
testwbook.set_range(2,1,['Number','Name'])
m2 = testwbook.save(full_name)
testwbook.close()
return m2
Main
root = Tk()
d = str(asksaveasfilename(parent=root,filetypes=[('Excel','*.xls')],title="Save report as..."))
d = d + '.xls'
d = d.replace('/','\\')
root.destroy()
Mode1(d)
Mode2(d)
And once in a while I get the following error:
Traceback (most recent call last):
File "T:\TEST\testpy.py", line 2035, in <module>
Mode2(d)
File ""T:\TEST\testpy.py"", line 1381, in Mode2
print type(full_name)
TypeError: 'str' object is not callable
Any idea why is this happening? How can I prevent it?
The only function call in the line you get the error is a call to the built-in function type(), so the only explanation for your error message is that you overwrote the built-in name type by a global name type pointing to a string object. Try adding
print type
before
print type(full_name)
It looks like somewhere you're setting a (global) variable named type to a string, thus overwriting the built-in type function.
Try searching your code for type = to see what turns up.
Understandably, Python would then throw that exception when you tried to call type (strings can't be "called").

Categories

Resources