熊猫无法读取保存在子文件夹

时间:2018-11-23 08:16:42

标签: python-3.x pandas

我在当前的工作目录中保存了5个json文件,下面的代码对我来说很不错,以便阅读每个文件以进行进一步分析:

import pandas as pd
import os
path=os.path.join('.') #Just want to as an example here
allfiles = os.listdir(path)
files = [files for files in allfiles if files.endswith('.json')]

for i in files:
    df=pd.read_json(i)
allfiles

但是当我在当前工作目录中创建一个子文件夹并将其5个json文件移至该文件夹时,我无法读取它们:

import pandas as pd
import os
path=os.path.join('.','Result')#New Folder:Result
allfiles = os.listdir(path)
files = [files for files in allfiles if files.endswith('.json')]

for i in files:
    df=pd.read_json(i)
allfiles

错误消息是: ValueError:尾随数据 我尝试通过Google搜索它,但仍然不知道发生了什么,我没有做任何更改,只是创建了一个子文件夹。

3 个答案:

答案 0 :(得分:2)

尝试当前工作目录,然后加入新的子目录。

Name

我刚刚在.pdf中测试了代码,因为我在Downloads目录中有pdf。

John, Donald, Jessika, ...

对我有用。

答案 1 :(得分:1)

使用熊猫打开文件时,仅传递文件名而不传递绝对路径。因此,当脚本从存在文件的当前目录运行时,便可以将其打开。 但是当您将文件移动到Result目录时,它仍在当前目录中搜索文件。

在下面的代码中进行了编辑,以在文件名数组中具有完整的目录路径。

cwd = os.getcwd()
path=os.path.join(cwd) #Just want to as an example here
allfiles = os.listdir(path)
files = [os.path.join(path,files) for files in allfiles if files.endswith('.json')]
print(files)

for f in files :
    df1 = pd.read_json(f)
print(df1.head(1))
  

['C:\ Users \ XXX \ XXX \ XXX \ all_data.json']

     

词汇    GlossDiv {'title':'S','GlossList':{'GlossEntry':   {'我...


path=os.path.join(cwd,'Result') #Just want to as an example here
allfiles = os.listdir(path)
files = [os.path.join(path,files) for files in allfiles if files.endswith('.json')]
print(files)
for f in files :
    df1 = pd.read_json(f)
print(df1.head(1))
  

['C:\ Users \ XXX \ XXX \ XXX \ Result \ all_data1.json']

     

词汇表GlossDiv {'title':'S','GlossList':{'GlossEntry':{'I ...

文件中的示例数据:

 {
        "glossary": {
            "title": "example glossary",
            "GlossDiv": {
                "title": "S",
                "GlossList": {
                    "GlossEntry": {
                        "ID": "SGML",
                        "SortAs": "SGML",
                        "GlossTerm": "Standard Generalized Markup Language",
                        "Acronym": "SGML",
                        "Abbrev": "ISO 8879:1986",
                        "GlossDef": {
                            "para": "A meta-markup language, used to create markup languages such as DocBook.",
                            "GlossSeeAlso": ["GML", "XML"]
                        },
                        "GlossSee": "markup"
                    }
                }
            }
        }
    }

答案 2 :(得分:1)

您可以使用glob.glob,它返回与您的pathname相匹配的路径的列表:

import glob
pathname = 'Result/*.json'
list_of_paths_to_files = glob.glob(pathname)

如果您要读取多个DataFrame个单独的文件:

list_of_dataframes = [pd.read_json(file_path) for file_path in list_of_paths_to_files]

如果您要一个DataFrame

df = pd.concat(list_of_dataframes)