Python pickle syntax - python

I'm using the latest python release and after searching, I can't seem to find anything on pickles that will work for me.
I am simply going through tutorials attempting to learn about pickling and none of the source code that apparently works on the tutorials will work for me, I suspect this is something to do with the tutorials being outdated.
What I have tried and is the same as what tutorials show is:
import pickle
lists = [1,2,3,4,5]
pickle.dump(lists, open('log.txt', 'a+'))
which gives me the following error:
Traceback (most recent call last):
File "<pyshell#2>", line 1, in <module>
pickle.dump(lists, open('log.txt', 'a+'))
TypeError: must be str, not bytes
this
>>> import pickle
>>> unpicklefile = open('log.txt', 'r')
>>> unpickledlist = [1,2,3,4,5]
>>> unpickledlist = pickle.load(unpicklefile)
gives me the following error:
Traceback (most recent call last):
File "<pyshell#3>", line 1, in <module>
unpickledlist = pickle.load(unpicklefile)
TypeError: 'str' does not support the buffer interface
Thank you for any replies and help

The 'a+' mode may be causing you problems. And, if you're on Windows, it would be useful to open a file in a binary mode. Also, you should close the file before reopening to read it back in. And make sure you're writing and reading the same file ('log.txt' vs. 'filename'):
import pickle
lists = [1,2,3,4,5]
f = open('tmp_pickle.pic', 'wb')
pickle.dump(lists, f)
f.close()
f = open('tmp_pickle.pic', 'rb')
unpickledlist = pickle.load(f)
print unpickledlist

Related

TypeError when reading CBOR file

I am working on a project using the CBOR file to contain data. I already install cbor with pip install cbor. But I cannot read it.
This is my code:
import cbor
cbor.loads(r"C:\Users\User\Desktop\project\score.cbor")
Then its return this error:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "C:\Users\User\Anaconda3\envs\pyenv\lib\site-packages\cbor\cbor.py", line 263, in loads
fp = StringIO(data)
TypeError: a bytes-like object is required, not 'str'
How to solve this problem? And is there a way to convert CBOR to JSON file because I find it easier to work with the JSON file in Python.
I still don't know how to solve this problem with cbor, I use cbor2 instead and it works.
import cbor2
path = "home/data/score.cbor"
with open(path, 'rb') as fp:
obj = cbor2.load(fp)
print(obj)
Output
{'root': {'probe': 20, 'candidate': 31}, 'tree': [], 'support': []}

Python get data from named pipe

How do I read from a named pipe in Python 3.5.3?
The pipe's name and location is /tmp/shairport-sync-metadata and it can be viewed by anybody, but only modified by the shairport-sync user.
Other websites and questions say to use os.mkfifo("pipe-location") but I've been getting this error:
>>> import os
>>> os.mkfifo("/tmp/shairport-sync-metadata")
Traceback (most recent call last):
File "<pyshell#1>", line 1, in <module>
os.mkfifo("/tmp/shairport-sync-metadata")
FileExistsError: [Errno 17] File exists
Is there a way to get around this? Sorry for the nooby question.
os.mkfifo is used to create fifo. Use open to open/read fifo already exist:
with open('/tmp/shairport-sync-metadata') as f: # add `rb` for binary mode
# line-by-line read
for line in f:
print(line)
# f.read(1024) # to read 1024 characters

Any ideas how to fix TypeError: 'str' does not support the buffer interface?

I keep getting this error "TypeError: 'str' does not support the buffer interface" Not sure what is going wrong. Any assistance would be great.
import zlib
#User input for sentnce & compression.
sentence = input("Enter the text you want to compress: ")
com = zlib.compress(sentence)
#Opening file to compress user input.
with open("listofwords.txt", "wb") as myfile:
myfile.write(com)
The error means that you are trying to pass str object (Unicode text) instead of binary data (byte sequence):
>>> import zlib
>>> zlib.compress('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: 'str' does not support the buffer interface
Python 3.5 improves the error message here:
>>> import zlib
>>> zlib.compress('')
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
To save text as binary data, you could encode it using a character encoding. To compress the data, you could use gzip module:
import gzip
import io
with io.TextIOWrapper(gzip.open('sentence.txt.gz', 'wb'),
encoding='utf-8') as file:
print(sentence, file=file)

Importing a file based upon the path

I have a python script that exports a file using the following command in a function. It's works, but I need to import that file after exporting and loop through it.
connector.save_csv(path,'_'+"GT_Weekly"+'_'+keys)
Thereore, I've been hard coding the file name and using it with open(). However, I was wondering how I could specify the file name in the same way as specified when I saved it.
Here's the hard coded approach:
with open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt') as csvfile:
csvReader = csv.reader(csvfile)
data = []
I want to take the save_csv arguments and add it to open but that doesn't work. How can I do this
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
Both keys and path were specified as
keys ="football"
path = "/home/abraham/Trends"
What component needs to be changed to an integer? It's not evident to me
Furthermore, when I add int,I get the following error
with int(open(path,'_'+"GT_Weekly"+'_'+keys+'.csv', 'rt')) as csvfile:
csvReader = csv.reader(csvfile)
data = []
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: an integer is required
>>>
You seem to think open accepts a path, a file name, and a mode; but it doesn't. The parameters are a file name, a mode, and a buffer size. The buffer size should be an integer, but you are passing 'rt'; hence, you get an error message.
I guess you want open(os.path.join(path, filename), 'rt') instead, or possibly open(path + filename, 'rt'), if the last component of path is a prefix part of the filename you want, not a directory name.

Trying to get an image with python

I am trying to get an image from a website and I don't know what i am doing wrong.
Here is my code:
import httplib2
h = httplib2.Http('.cache')
response, content = h.request('http://1.bp.blogspot.com/-KSBzFF0bIyU/TtFyj-KgC0I/AAAAAAAABEo/o43IoY_9Bec/s1600/praia-de-ponta-verde-maceio.jpg')
print(response.status)
with open('maceio.jpg', 'wb') as f:
print(content, file = f)
--------------------------------------------------------------------------------
200
Traceback (most recent call last):
File "/home/matheus/workspace/Get Link/new_method_v2.py", line 12, in <module>
print(content, file = f)
TypeError: 'str' does not support the buffer interface
The error is caused by the following line:
print(content, file = f)
print implicitely converts the bytes object named content to a string (str object), which cannot be written to a file in binary mode, since Python does not know which character encoding to use.
Why are you taking the print detour at all? Just write the contents to the file using the file.write() method:
with open('maceio.jpg', 'wb') as f:
f.write(content)

Categories