gpt4 book ai didi

python - 类型错误 : file must have 'read' and 'readline' attributes

转载 作者:行者123 更新时间:2023-12-05 00:56:27 24 4
gpt4 key购买 nike

第一种方法:我试图让下面的代码从早上开始工作。我已经在 stackoverflow 和谷歌上关于 python 的教程中阅读了很多答案,我已经完成了 0 个进度。你能帮我解决这个错误吗:

Using TensorFlow backend.
Traceback (most recent call last):
File "source_code_modified.py", line 65, in <module>
dict1 = pickle.load(f1,encoding='bytes')
TypeError: file must have 'read' and 'readline' attributes

爆出来的代码就是这部分:

class load_train_data:
os.open("/home/just_learning/Desktop/CNN/datasets/training_data/images", os.O_RDONLY)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass


class load_test_data:
os.open("/home/just_learning/Desktop/CNN/datasets/test_data/images",os.O_RDONLY)
def __enter__(self):
return self
def __exit__(self, type, value, traceback):
pass


with load_train_data() as f1:
dict1 = pickle.load(f1,encoding='bytes')

第二种方法:

好的,我做到了,错误是:

Using TensorFlow backend.
Traceback (most recent call last):
File "source_code_modified.py", line 74, in <module>
with open_train_data() as f1:
File "source_code_modified.py", line 47, in open_train_data
return open('/home/just_learning/Desktop/CNN/datasets/training_data/images','rb')
IsADirectoryError: [Errno 21] Is a directory: '/home/just_learning/Desktop/CNN/datasets/training_data/images'

代码在这些点上爆炸:

def open_train_data():
return open('/home/just_learning/Desktop/CNN/datasets/training_data/images','rb') <--- explodes here

def open_test_data():
return open('/home/just_learning/Desktop/CNN/datasets/test_data/images','rb')

with open_train_data() as f1:
dict1 = pickle.load(f1) <--- explodes here

第三种方法:我发现了这个:"IsADirectoryError: [Errno 21] Is a directory: " It is a file

我将代码更改为:

def open_train_data():
return os.listdir('/home/just_learning/Desktop/CNN/datasets/training_data/images')

def open_test_data():
return os.listdir('/home/just_learning/Desktop/CNN/datasets/test_data/images')

with open_train_data() as f1: <-------------- explodes here
dict1 = pickle.load(f1) #,encoding='bytes')

错误是这样的:

Using TensorFlow backend.
Traceback (most recent call last):
File "source_code_modified.py", line 74, in <module>
with open_train_data() as f1:
AttributeError: __enter__

我通过在 github/google 中搜索解决了这个错误,这是我在上面发布的第一种方法中描述的结果......

最佳答案

使用类似的东西:

def open_test_data():
return open('path/to/filename', 'rb')

with open_test_data() as f:
dict1 = pickle.load(f)

没有理由尝试为这样的事情定义自己的上下文管理器。

编辑:您最初的第一次尝试是 encoding='bytes'。根据数据的来源,您可能需要添加它。

关于python - 类型错误 : file must have 'read' and 'readline' attributes,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/62312308/

24 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com