簡體   English   中英

瀏覽Python中的所有文件夾

[英]Going through all folders in Python

我想瀏覽目錄內的所有文件夾:

directory\  
   folderA\
         a.cpp
   folderB\
         b.cpp
   folderC\
         c.cpp
   folderD\
         d.cpp

文件夾的名稱都是已知的。 具體來說,我正在嘗試計算a.cppb.cppc.ppd.cpp源文件上的代碼行數。 因此,進入folderA並讀取a.cpp ,計算行數,然后返回目錄,進入folderB ,讀取b.cpp ,計數行等。

這是我到目前為止所擁有的,

dir = directory_path
for folder_name in folder_list():
    dir = os.path.join(dir, folder_name)
    with open(dir) as file:
        source= file.read()
    c = source.count_lines()

但是我是Python的新手,不知道我的方法是否合適以及如何進行。 顯示的任何示例代碼將不勝感激!

另外, with open是否可以像所有這些讀取一樣處理文件打開/關閉,還是需要更多處理?

我會這樣做:

import glob
import os

path = 'C:/Users/me/Desktop/'  # give the path where all the folders are located
list_of_folders = ['test1', 'test2']  # give the program a list with all the folders you need
names = {}  # initialize a dict

for each_folder in list_of_folders:  # go through each file from a folder
    full_path = os.path.join(path, each_folder)  # join the path
    os.chdir(full_path)  # change directory to the desired path

    for each_file in glob.glob('*.cpp'):  # self-explanatory
        with open(each_file) as f:  # opens a file - no need to close it
            names[each_file] = sum(1 for line in f if line.strip())

    print(names)

輸出:

{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2}
{'file1.cpp': 2, 'file3.cpp': 2, 'file2.cpp': 2}

關於with問題,您不需要關閉文件或進行任何其他檢查。 您現在應該很安全。

但是, 您可能會檢查full_path存在,因為有人(您)可能會錯誤地從PC刪除文件夾( list_of_folders的文件夾)

您可以通過os.path.isdir來執行此操作,如果文件存在,則返回True

os.path.isdir(full_path)

PS:我使用了Python 3。

使用Python 3的os.walk()遍歷給定路徑的所有子目錄和文件,打開每個文件並執行邏輯。 您可以使用“ for”循環來遍歷它,從而大大簡化您的代碼。

https://docs.python.org/2/library/os.html#os.walk

正如manglano所說,os.walk()

您可以生成文件夾列表。

[src for src,_,_ in os.walk(sourcedir)]

您可以生成文件路徑列表。

[src+'/'+file for src,dir,files in os.walk(sourcedir) for file in files]

暫無
暫無

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

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