[英]how to import and read multiple json files in pandas?
我正在嘗試使用 python 讀取多個 json 文件。 我的文件看起來像這樣:
如您所見,所有 json 文件都具有相同的名稱,只是文件夾名稱不同。 有沒有辦法讀取收件箱並遍歷每個文件夾以獲取json文件?
到目前為止,我有這個:
path = '/messages/inbox/'
file= '/message_1.json'
並且在想這樣的事情:
for i in <something?> :
new_file = path + str(i) + file
with open('new_file', 'r') as myfile:
data=myfile.read()
obj = json.loads(data)
我知道這行不通,因為 python 需要先讀取路徑。 如何讓程序讀取路徑然后遍歷它?
感謝您花時間閱讀我的問題並以任何方式提供幫助。
您可以使用方法os.listdir("relative path to where the folders are")
(看看 domumentation)來獲取 cwd 中的所有子目錄。 並且您不應該使用負載來獲取文件的內容,而是將文件對象傳遞給json.load()
方法。 在你的代碼中實現它會是這樣的:
import os
for i in os.listdir(path) :
new_file = path + i + file
my_file = open(new_file,"r")
obj = json.load(my_file)
my_file.close()
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.