簡體   English   中英

從python中的文件夾中讀取多個.txt文件的名稱

[英]Reading names of multiple .txt files from a folder in python

有沒有辦法從單個文件夾中讀取多個 .txt 文件的名稱? 我現在只能讀取文件的內容。

import glob
import errno
path = 'C:/Users/rabhi/Desktop/NLP/aclImdb/test/neg/*.txt'
files = glob.glob(path)
for name in files:
    try:
        with open(name) as f:
            for line in f:
                print(line.split())
    except IOError as exc: 
        if exc.errno != errno.EISDIR:
            raise 

您可以為此使用os.walk()

import os
def main():
    for dirName, subDirList, fileList in os.walk('path'):
        for subDir in subDirList:
            for file in fileList:
                #Do something with file
main()

這會遞歸地遍歷給定目錄中的文件。 要忽略子目錄,您可以嘗試以下操作:

import os
def main():
    for dirName, subDirList, fileList in os.walk('path'):
        for file in fileList:
            #Do something with file
main()

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM