使用Python从文件目录导入多个选定的json文件

使用Python从文件目录导入多个选定的json文件,python,json,pandas,import,Python,Json,Pandas,Import,我在文件夹中有23000多个json文件 出于测试目的,我只想读取10个文件 # Read several files file1 = 'tweets201706221015.json' file2 = 'tweets201706221115.json' file3 = 'tweets201706221215.json' file4 = 'tweets201706221315.json' file5 = 'tweets201706221415.json' file6 = 'tweets20170

我在文件夹中有23000多个json文件

出于测试目的,我只想读取10个文件

# Read several files
file1 = 'tweets201706221015.json'
file2 = 'tweets201706221115.json'
file3 = 'tweets201706221215.json'
file4 = 'tweets201706221315.json'
file5 = 'tweets201706221415.json'
file6 = 'tweets201706221515.json'
file7 = 'tweets201706221615.json'
file8 = 'tweets201706221715.json'
file9 = 'tweets201706221815.json'
file10 = 'tweets201706221915.json'
甚至更好-随机选择10个json文件。

我找到了这个答案,但它只是从文件夹中读取
json
文件,这对我来说不是问题。我只需要一小部分数据

我的代码:

directory = some directory
files = [file1, file2, file3, file4, file5, file6, file7, file8, file9, file10]

path = directory + files

如上文注释部分所述,只需建立一个普通列表并迭代每个文件名,例如:

#For simplicity reasons just three files - you can use a generator or read the filenames from the directory
files = ['file1.json', 'file2.json', 'file3.json']

for file in files:
   f = open(file)
   #Do your stuff with the file
   f.close()

如上文注释部分所述,只需建立一个普通列表并迭代每个文件名,例如:

#For simplicity reasons just three files - you can use a generator or read the filenames from the directory
files = ['file1.json', 'file2.json', 'file3.json']

for file in files:
   f = open(file)
   #Do your stuff with the file
   f.close()
首先使用os.listdir()从目录中获取所有JSON文件的列表,然后从该列表中随机选择10个文件。最后,您可以使用普通打开函数循环加载这10个文件

这将有助于随机选择

首先使用os.listdir()从目录中获取所有JSON文件的列表,然后从该列表中随机选择10个文件。最后,您可以使用普通打开函数循环加载这10个文件

这将有助于随机选择

对于目录中的随机选取

import os
import random 

# pick ten files from the /json/dir directory
ten_files = random.choices(os.listdir('/json/dir'), k=10)

for fi in ten_files:
    with open(f'/json/dir/{fi}') as in_file:
        # do something with in_file

对于目录中的随机选取

import os
import random 

# pick ten files from the /json/dir directory
ten_files = random.choices(os.listdir('/json/dir'), k=10)

for fi in ten_files:
    with open(f'/json/dir/{fi}') as in_file:
        # do something with in_file

你到底有什么问题?您没有包含任何方法或代码-您是否尝试过迭代您的文件并逐个读取每个文件?我尝试创建一个文件列表
files=[file1,file2,file3,file4,file5,file6,file7,file8,file9,file10]
,然后读取为
path=directory+files
,但并没有那么简单。谢谢就是这么简单!请用代码更新您的问题,否则我们很难调试。您的确切问题是什么?您没有包含任何方法或代码-您是否尝试过迭代您的文件并逐个读取每个文件?我尝试创建一个文件列表
files=[file1,file2,file3,file4,file5,file6,file7,file8,file9,file10]
,然后读取为
path=directory+files
,但并没有那么简单。谢谢就是这么简单!请用代码更新您的问题,否则我们很难调试。太好了!谢谢你的时间!精彩的!谢谢你的时间!