[英]Python: Finding files in directory but ignoring folders and their contents
So my program search_file.py is trying to look for.log files in the directory it is currently placed in. I used the following code to do so:所以我的程序 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)
My current directory is as follows:我当前目录如下:
search_file.py搜索文件.py
sample_1.log示例_1.log
sample_2.log样本_2.log
extra_file (this is a folder) extra_file(这是一个文件夹)
And within the extra_file folder we have:在 extra_file 文件夹中,我们有:
extra_sample_1.log extra_sample_1.log
extra_sample_2.log extra_sample_2.log
Now, when the program runs and prints the files out it also takes into account the.log files in the extra_file folder.现在,当程序运行并打印出文件时,它还会考虑 extra_file 文件夹中的 .log 文件。 But I do not want this.但我不想要这个。 I only want it to print out sample_1.log and sample_2.log.我只希望它打印出 sample_1.log 和 sample_2.log。 How would I approach this?我将如何处理这个?
Try this:尝试这个:
import os
files = os.listdir()
for file in files:
if file.endswith('.log'):
print(file)
The problem in your code is os.walk
traverses the whole directory tree and not just your current directory.您的代码中的问题是os.walk
遍历整个目录树而不仅仅是您的当前目录。 os.listdir
returns a list of all filenames in a directory with the default being your current directory which is what you are looking for. os.listdir
返回目录中所有文件名的列表,默认情况下是您正在寻找的当前目录。
By default, os.walk
does a root-first traversal of the tree, so you know the first emitted data is the good stuff.默认情况下, os.walk
对树进行根优先遍历,因此您知道第一个发出的数据是好东西。 So, just ask for the first one.所以,只要求第一个。 And since you don't really care about root or dirs, use _
as the "don't care" variable name由于您并不真正关心 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)
Its also common to use glob:使用 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)
This runs the risk that there is a directory that ends in ".log", so you could also add a testing using os.path.isfile(file)
.这存在以“.log”结尾的目录的风险,因此您还可以使用os.path.isfile(file)
添加测试。
声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.