簡體   English   中英

Python:在目錄中查找文件但忽略文件夾及其內容

[英]Python: Finding files in directory but ignoring folders and their contents

所以我的程序 search_file.py 正在嘗試在它當前所在的目錄中查找 .log 文件。我使用以下代碼來執行此操作:

import os

# This is to get the directory that the program is currently running in
dir_path = os.path.dirname(os.path.realpath(__file__))

# for loop is meant to scan through the current directory the program is in
for root, dirs, files in os.walk(dir_path):
    for file in files:
        # Check if file ends with .log, if so print file name
        if file.endswith('.log')
            print(file)

我當前目錄如下:

搜索文件.py

示例_1.log

樣本_2.log

extra_file(這是一個文件夾)

在 extra_file 文件夾中,我們有:

extra_sample_1.log

extra_sample_2.log

現在,當程序運行並打印出文件時,它還會考慮 extra_file 文件夾中的 .log 文件。 但我不想要這個。 我只希望它打印出 sample_1.log 和 sample_2.log。 我將如何處理這個?

嘗試這個:

import os

files = os.listdir()

for file in files:
    if file.endswith('.log'):
        print(file)

您的代碼中的問題是os.walk遍歷整個目錄樹而不僅僅是您的當前目錄。 os.listdir返回目錄中所有文件名的列表,默認情況下是您正在尋找的當前目錄。

os.walk 文檔

os.listdir 文檔

默認情況下, os.walk對樹進行根優先遍歷,因此您知道第一個發出的數據是好東西。 所以,只要求第一個。 由於您並不真正關心 root 或 dirs,因此使用_作為“不關心”變量名

# get root files list.
_, _, files = next(os.walk(dir_path))
for file in files:
    # Check if file ends with .log, if so print file name
    if file.endswith('.log')
        print(file)

使用 glob 也很常見:

from glob import glob
dir_path = os.path.dirname(os.path.realpath(__file__))
for file in glob(os.path.join(dir_path, "*.log")):
    print(file)

這存在以“.log”結尾的目錄的風險,因此您還可以使用os.path.isfile(file)添加測試。

暫無
暫無

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

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