只读取 python 中顶级目录中的文件

Reading only the files in top directory in python

我有一个包含许多 .txt 文件的目录,该目录包含另一个包含 .json 文件的目录。我试图只读取文本文件并对它们应用函数,然后读取 JSON 文件并对这些文件应用不同的函数。如何单独访问每种文件类型而不是一次访问所有文件和目录?这是一个基本代码片段,用于说明我正在尝试做的事情。

textfiles = glob.glob(os.path.join(rootdir, '*.txt'))
jsonfiles = glob.glob(os.path.join(rootdir, '*.json'))

for f in textfiles:
    title = linecache.getline(f,1)
    titles = title[1:-1].split(',')#to convert what I read into list.
    do other stuff here...
    for item in titles:
        with open(f,"r") as fi:
            poems = json.load(fi)
        for fi in jsonfiles:
            with open(fi,"r") as file:
                poems = json.load(file)
            if(song["title"]==item):
                print(item)

如果您只需要一个目录中的文件,请不要使用 os.walk()

您可以使用 glob module 轻松收集特定类型的文件:

import glob
import os.path

textfiles = glob.glob(os.path.join(rootdir, '*.txt'))
jsonfiles = glob.glob(os.path.join(rootdir, 'subdue', '*.json'))

这些 glob 只会找到文本 rootdir 和(命名的)子目录中的 JSON 文件。

from os import listdir
from os.path import isfile, join
onlyfiles = [ f for f in listdir(mypath) if isfile(join(mypath,f)) ]
onlytxtfiles = filter(onlyfiles, lambda(filename):filename.endswith('.txt'))
for fname in onlytxtfiles:
   ...

填写您想代替 ... 做的事情,如果您需要进一步的帮助,请告诉我。