Hello I have an Error and I don´t the reason:
>>> class Fruits:pass
...
>>> banana = Fruits()
>>> banana.color = 'yellow'
>>> banana.value = 30
>>> import pickle
>>> filehandler = open("Fruits.obj",'w')
>>> pickle.dump(banana,filehandler)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Python31\lib\pickle.py", line 1354, in dump
Pickler(file, protocol, fix_imports=fix_imports).dump(obj)
TypeError: must be str, not bytes
>>>
I don´t know how to solve this error because I don´t understand it.
Thank you so much.
You have to open your filehandler in binary mode, use wb instead of w:
filehandler = open(b"fruits.obj","wb")
Related
I am trying to write to a FieldFile of an instance of a model:
class SourceFile(models.Model):
file_name = models.CharField('File Name', max_length = 100, unique=True)
import_time = models.DateTimeField('Import Time', auto_now_add = True)
local_link = models.FileField(upload_to="ozio/uploaded_files/%Y")
Having no problem when I create the file with:
source_file = SourceFile.objects.create(file_name = source_file_name)
source_file.local_link.save(source_file.file_name, ContentFile('LINE1'))
However when I tried to append new lines:
source_file.local_link.open('a') # Open as append mode
source_file.local_link.write('LINE2')
It complains:
Traceback (most recent call last):
File "<console>", line 1, in <module>
io.UnsupportedOperation: write
When close it and reopen, everything looks ok. Grateful for any suggestion.
>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link
<FieldFile: ozio/uploaded_files/2014/Manual.2014.Q2.csv>
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
Traceback (most recent call last):
File "<console>", line 1, in <module>
io.UnsupportedOperation: write
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE2')
5
>>> source_file.local_link.close()
>>> source_file, created = SourceFile.objects.get_or_create(file_name = 'Manual.2014.Q2.csv')
>>> source_file.local_link.open('a')
>>> source_file.local_link.close()
>>> source_file.local_link.open('a')
>>> source_file.local_link.write('LINE3')
5
>>> source_file.local_link.close()
>>>
How can I check if an object is a file?
>>> f = open("locus.txt", "r")
>>> type(f)
<class '_io.TextIOWrapper'>
>>> isinstance(f, TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#7>", line 1, in <module>
isinstance(f, TextIOWrapper)
NameError: name 'TextIOWrapper' is not defined
>>> isinstance(f, _io.TextIOWrapper)
Traceback (most recent call last):
File "<pyshell#8>", line 1, in <module>
isinstance(f, _io.TextIOWrapper)
NameError: name '_io' is not defined
>>> isinstance(f, _io)
Traceback (most recent call last):
File "<pyshell#9>", line 1, in <module>
isinstance(f, _io)
NameError: name '_io' is not defined
>>>
I have the variable f that is a text file. When I print the type of f the Python3 interpreter shows '_io.TextIOWrapper', but if I check it with isinstance() function throws exception: NameError.
_io is the C implementation for the io module. Use io.IOBase for direct subclasses, after importing the module:
>>> import io
>>> f = open("tests.py", "r")
>>> isinstance(f, io.IOBase)
True
I got an error while run python proxy.py
$ python proxy.py
INFO - [Sep 28 14:59:19] getting appids from goagent plus common appid pool!
Traceback (most recent call last):
File "proxy.py", line 2210, in <module>
main()
File "proxy.py", line 2180, in main
pre_start()
File "proxy.py", line 2157, in pre_start
common.set_appids(get_appids())
File "proxy.py", line 94, in get_appids
fly = bytes.maketrans(
AttributeError: type object 'str' has no attribute 'maketrans'
The proxy.py file in https://code.google.com/p/smartladder/,
def get_appids():
fly = bytes.maketrans(
b"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
b"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib.request.urlopen(url="http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = str(d, encoding='ascii').split('\r\n')
random.shuffle(e)
return e
You are running code written for Python 3, with Python 2. This won't work.
maketrans is a classmethod on the bytes built-in type, but only in Python 3.
# Python 3
>>> bytes
<class 'bytes'>
>>> bytes.maketrans
<built-in method maketrans of type object at 0x10aa6fe70>
In Python 2, bytes is an alias for str, but that type does not have that method:
# Python 2.7
>>> bytes
<type 'str'>
>>> bytes.maketrans
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
AttributeError: type object 'str' has no attribute 'maketrans'
Run your code with Python 3 instead, or translate all code in this project to Python 2; the latter requires in-depth knowledge of how Python 2 and 3 differ and is likely a major undertaking.
Just the illustrated function, translated to Python 2, would be:
import string
import urllib2
import base64
import random
def get_appids():
fly = string.maketrans(
"abcdefghijklmnopqrstuvwxyzABCDEFGHIJKLMNOPQRSTUVWXYZ",
"nopqrstuvwxyzabcdefghijklmNOPQRSTUVWXYZABCDEFGHIJKLM"
)
f = urllib2.urlopen("http://lovejiani.com/v").read().translate(fly)
d = base64.b64decode(f)
e = unicode(d, encoding='ascii').split(u'\r\n')
random.shuffle(e)
return e
I'm having issues accessing a COM object using the Python win32com module, which I don't have when using VBA. See usage/error below. The other parts of the object are functioning OK, but I can't get any of the parameters out of the ResultSet object.
>>> import win32com.client
>>> Aquator = win32com.client.gencache.EnsureDispatch("Aquator.Application")
>>> db = Aquator.LoadDatabase(r"D:\Shared", "AquatorExcel.mdb")
>>> project = Aquator.LoadProject(db, "A simple model", False, False)
>>>
>>> project.ModelRunStart()
<win32com.gen_py.Aquator Water Resource Simulation._ModelRun instance at 0x15264
824>
>>> Aquator.ActiveProject.ModelRuns.Count
1
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet
<win32com.gen_py.Aquator Water Resource Simulation._IResultSet instance at 0x149
19000>
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.Cost
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 463, in __getattr__
return self._ApplyTypes_(*args)
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 456, in _ApplyTypes_
self._oleobj_.InvokeTypes(dispid, 0, wFlags, retType, argTypes, *args),
pywintypes.com_error: (-2147352573, 'Member not found.', None, None)
The equivalent code in the VBA editor within the application functions correctly, returning a float:
Public Sub Test()
MsgBox Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.Cost
End Sub
As far as I can tell, the EnsureDispatch command has done it's job correctly, and recognises the property (along with others, also inaccessible):
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet._prop_map_get_.keys()
['WaterBalanceMl', 'RunDate', 'Parameters', 'DoublePrecision', 'WarningCount', '
FinishDate', 'AmountLost', 'SinglePrecision', 'Status', 'StartDate', 'Descriptio
n', 'AmountLeaked', 'FailureCount', 'AmountAdded', 'ErrorCount', 'AmountStored',
'Name', 'WaterBalancePercent', 'InfoValueList', 'Results', 'States', 'Cost', 'A
mountRemoved', 'Sequences', 'Duration', 'InfoNameList', 'RunTime']
>>> Aquator.ActiveProject.ModelRuns.Item(1).ResultSet.meh
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Program Files\Pythonxy\Pythonxy 2.7\Python27\lib\site-packages\win32c
om\client\__init__.py", line 462, in __getattr__
raise AttributeError("'%s' object has no attribute '%s'" % (repr(self), attr
))
AttributeError: '<win32com.gen_py.Aquator Water Resource Simulation._IResultSet
instance at 0x15175888>' object has no attribute 'meh'
I have tried using .GetCost() (a la Setting a property using win32com), to no avail ("object has no attribute...").
What am I doing wrong here?
It seems the problem is with the win32com module. The equivilent code using the comtypes module functions correctly:
>>> from comtypes.client import CreateObject
>>> Aquator = CreateObject("Aquator.Application")
>>> Database = Aquator.LoadDatabase(r"D:\Shared", "AquatorExcel.mdb")
>>> Project = Aquator.LoadProject(Database, "A simple project", False, False)
>>> ModelRun = Project.ModelRunStart()
>>> print ModelRun.ResultSet.Cost
133432.20
When I test my code:
def read_classification_from_file(path, name):
path = add_slash(path) + name
myfile = open(path, "r")
mydict = {}
for line in myfile():
x = line.split(" ")
x[1]=x[1].replace("\n","")
mydict[x[0]]=x[1]
return mydict
def add_slash(path):
if path.endswith('/'): return path
return path + '/'
I receive error :
Traceback (most recent call last):
File "spamfilter/solution/test_quality_for_corpus.py", line 59, in test_allPredictionsHam
q = self.compute_quality_for_corpus(CORPUS_DIR)
File "/local/ulohy/env/data/4893_1/quality.py", line 9, in compute_quality_for_corpus
truth_dic = utils.read_classification_from_file(corpus_dir, "!truth.txt")
File "/local/ulohy/env/data/4893_1/utils.py", line 5, in read_classification_from_file
for line in myfile():
TypeError: '_io.TextIOWrapper' object is not callable
So, I just font understand, where the error is.
Thank you!
You just want for line in myfile:. file objects can be iterated over directly (yielding 1 line at a time). However, file objects don't support calling (e.g. myfile() isn't implemented because file.__call__ isn't implemented).