我只是想用Python读取我的json文件。当我这样做时,我在正确的文件夹中;我在下载中,我的文件名为'Books_5.json'。但是,当我尝试使用.read()函数时,我收到错误
OSError: [Errno 22] Invalid argument
这是我的代码:
import json
config = json.loads(open('Books_5.json').read())
这也引发了同样的错误:
books = open('Books_5.json').read()
如果有帮助,这是我的数据的一小部分:
{"reviewerID": "A10000012B7CGYKOMPQ4L", "asin": "000100039X", "reviewerName": "Adam", "helpful": [0, 0], "reviewText": "Spiritually and mentally inspiring! A book that allows you to question your morals and will help you discover who you really are!", "overall": 5.0, "summary": "Wonderful!", "unixReviewTime": 1355616000, "reviewTime": "12 16, 2012"}
{"reviewerID": "A2S166WSCFIFP5", "asin": "000100039X", "reviewerName": "adead_poet@hotmail.com \"adead_poet@hotmail.com\"", "helpful": [0, 2], "reviewText": "This is one my must have books. It is a masterpiece of spirituality. I'll be the first to admit, its literary quality isn't much. It is rather simplistically written, but the message behind it is so powerful that you have to read it. It will take you to enlightenment.", "overall": 5.0, "summary": "close to god", "unixReviewTime": 1071100800, "reviewTime": "12 11, 2003"}
我在MacOSX上使用Python 3.6
答案 0 :(得分:9)
这似乎是文件过大时发生的某种错误(我的文件大约为10GB)。一旦我使用split
将文件分解为200 k行,.read()
错误就会消失。即使文件不是严格的json格式也是如此。
答案 1 :(得分:0)
为了阅读json
文件,您可以使用下一个示例:
with open('your_data.json') as data_file:
data = json.load(data_file)
print(data)
print(data[0]['your_key']) # get value via key.
并尝试将json
个对象转换为列表
[
{'reviewerID': "A10000012B7CGYKOMPQ4L", ....},
{'asin': '000100039X', .....}
]
答案 2 :(得分:0)
您的代码看起来很好,看起来您的json数据格式不正确。请尝试以下方法。正如其他人所建议的那样,它应采用[{},{},...]的形式。
[{"reviewerID": "A10000012B7CGYKOMPQ4L", "asin": "000100039X",
"reviewerName": "Adam", "helpful": [0, 0], "reviewText": "Spiritually and
mentally inspiring! A book that allows you to question your morals and will
help you discover who you really are!", "overall": 5.0, "summary":
"Wonderful!", "unixReviewTime": 1355616000, "reviewTime": "12 16, 2012"},
{"reviewerID": "A2S166WSCFIFP5", "asin": "000100039X", "reviewerName":
"adead_poet@hotmail.com \"adead_poet@hotmail.com\"", "helpful": [0, 2],
"reviewText": "This is one my must have books. It is a masterpiece of
spirituality. I'll be the first to admit, its literary quality isn't much.
It is rather simplistically written, but the message behind it is so
powerful that you have to read it. It will take you to enlightenment.",
"overall": 5.0, "summary": "close to god", "unixReviewTime": 1071100800,
"reviewTime": "12 11, 2003"}]
您的代码和此数据适用于Windows 7和python 2.7。与您的设置不同,但仍然可以。