Django FieldFile cannot write on the first open - python

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()
>>>

Related

movie imdb get the id of the actor

I have an actor object, and it has both name and id, i could take the name, but it couldn't take the id
look please
>>> actor
<Person id:0000199[http] name:_Pacino, Al_>
>>> actor["name"]
u'Al Pacino'
>>> actor["id"]
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Library/Frameworks/Python.framework/Versions/2.7/lib/python2.7/site-packages/IMDbPY-5.0-py2.7-macosx-10.6-intel.egg/imdb/utils.py", line 1469, in __getitem__
rawData = self.data[key]
KeyError: 'id'
>>>
Use the .personID property of a Person object:
actor.personID

Why has this UnpicklingError occurred?

One one file, I have written:
import pickle
with open('pickle test2.py', 'wb') as p:
var = {1: "a", 2: "b"}
pickle.dump(var, p)
On another ('pickle test.py') the pickled version of the var dict is being stored.
And on a separate file I have attempted to load this dict, but an UnpicklingError has occurred. I wrote:
import pickle
with open('pickle test2.py', 'rb') as p:
var = pickle.load(p)
This was the error message:
Traceback (most recent call last):
File "C:/Users/Nathan/Python/pickle test open.py", line 4, in <module>
var = pickle.load(p)
_pickle.UnpicklingError
What does this mean, and how can it be resolved?

How can I check if an object is a file with isinstance()?

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

"Member not found." error using win32com

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

Python: saving objects and using pickle. Error using pickle.dump

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")

Categories