Error in opening of file. Python - python

I trying to open file and met some problem:
TypeError: coercing to Unicode: need string or buffer, NoneType found
Here is the code example:
a = open(fname, "rb").read(255)
Whats wrong with the code?

fname is None, not a string:
>>> open(None)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, NoneType found
You'll have to fix how you set fname or explicitly guard against it being None.

Related

How to properly write an 'If in' statement for an encoded string?

I'm trying to take the string hello, encode it into hexadecimal, and then print success if the value of t is found in the encoded string.
This is what I have currently:
import codecs
t='68656c6c6df'
pkts = ("hello")
pkts1 = codecs.encode(b'hello', 'hex_codec')
if "t" in pkts1:
print ('success')
Which gives me the error:
Traceback (most recent call last):
File "C:/Users/K/.PyCharmCE2018.1/config/scratches/scratch_1.py", line 8, in <module>
if "t" in pkts1:
TypeError: a bytes-like object is required, not 'str'

Not able to open and load pickle file in python 3.6.1

I am trying to open and load pickle file but by two ways. But every time I am getting an error.
Request you to please help.
First way :
enron_data = pickle.load(open("D:/New/ud120-projects/final_project/final_project_dataset.pkl", "r"))
Error: Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: a bytes-like object is required, not 'str'
Second Way :
enron_data = pickle.load(open("D:/New/ud120-projects/final_project/final_project_dataset.pkl", "rb"))
Error : Traceback (most recent call last):
File "<stdin>", line 1, in <module>
_pickle.UnpicklingError: the STRING opcode argument must be quoted
Request you to please help
If you are on Windows you have to use a raw string and backslashes like this:
r'D:\path\to\your\file'

An Error: 'Numpy.str_' object has no attribute 'decode'

I tried to run a test on Crab(an open source recommender system) based on python3. Then an error occurred:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 201, in load_sample_movies
data_songs[u_ix][i_ix] = float(rating)
ValueError: could not convert string to float: "b'3.0'"
I tried to use 'decode()' to convert the string, but it's not working:
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
File "/Users/Dennis/anaconda/lib/python3.5/site-packages/scikits/crab/datasets/base.py", line 202, in load_sample_movies
rating = rating.decode('utf-8')
AttributeError: 'numpy.str_' object has no attribute 'decode'
Any help will be appreciated!
The problem is that rating is a string within a string, so when you try casting a string like "b'3.0'" into a float, it gives a valueError because you still have the b in front which cannot be converted into float.
I imagine you need the byte encoding in front of the '3.0', so one way would be to evaluate rating to convert it from a string to bytes before typecasting it into a float (beware though, eval can have some safety issues).
>>> type(eval(rating))
<class 'bytes'>
>>> data_songs[u_ix][i_ix] = float(eval(rating))

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)

Python, os.listdir() error

I'm writing this procedure
def get_special_paths(dir):
detected_paths = []
paths = os.listdir(dir)
for path in paths:
if path == r'__\w+__':
detected_paths.append(path)
for element in detected_paths:
index = detected_path.index(element)
detected_paths[index] = os.path.abspath(element)
return detected_paths
and it raises a a type error as below:
Traceback (most recent call last):
File"copyspecial.py", line 65, in <module>
get_special_paths(dir)
File"copysepcial.py", line 23, in get_special_paths
paths = os.listdir(pathname)
TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found
What's the meaning of that error and how do I fix it? Thanks in advance :)
It seems like you passed the dir builtin function to the get_special_paths
>>> dir
<built-in function dir>
>>> os.listdir(dir)
Traceback (most recent call last):
File "<stdin>", line 1, in <module>
TypeError: coercing to Unicode: need string or buffer, builtin_function_or_method found
Pass the path as string.
get_special_paths('/path/to/dir')
BTW, don't use dir as a variable name. It will shadow the above dir function.
May be because global_path is not defined here:
for element in detected_paths:
index = detected_path.index(element) # Here detected_path is undefined
make it global_paths and try:
for element in detected_paths:
index = detected_paths.index(element)

Categories