Python:搜索给定路径中的文件,但不搜索给定路径目录中的文件
我有一些代码需要循环遍历给定路径上的所有文件。但是我注意到出现了一些奇怪的错误,结果我的代码不仅搜索给定路径上的文件,而且搜索位于同一路径的文件夹中的所有文件 例如Python:搜索给定路径中的文件,但不搜索给定路径目录中的文件,python,Python,我有一些代码需要循环遍历给定路径上的所有文件。但是我注意到出现了一些奇怪的错误,结果我的代码不仅搜索给定路径上的文件,而且搜索位于同一路径的文件夹中的所有文件 例如path=/home/Documents/place\u to\u check At path: file1.txt file2.txt file3.txt folder_containing_other_files 我只想循环浏览这3个文件,忽略文件夹中包含其他文件的所有文件 我的代码当前看起来像:
path=/home/Documents/place\u to\u check
At path:
file1.txt
file2.txt
file3.txt
folder_containing_other_files
我只想循环浏览这3个文件,忽略文件夹中包含其他文件的所有文件
我的代码当前看起来像:
for root, dirs, files in os.walk(path):
for file in files:
#Search for file
if file == "specific_file_I_want.json":
print "FOUND FILE"
我试图从第一行删除dirs
,但它抛出错误:
ValueError: too many values to unpack
任何建议都很好 如果不需要查看子目录,可以使用
for item in os.listdir(path):
if os.path.isfile(item):
print item
如果不需要查看子目录,可以使用
for item in os.listdir(path):
if os.path.isfile(item):
print item
更新:如果使用os.listdir
:
import os
all_files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path, i))]
#Search for file
if "specific_file_I_want.json" in all_files:
print "FOUND FILE"
如果使用os.walk
:
all_files = [ files for root, _, files in os.walk(path) if os.path.abspath(root) == os.path.abspath(path) ][0]
if "specific_file_I_want.json" in all_files:
print "FOUND FILE"
更新:如果使用os.listdir
:
import os
all_files = [i for i in os.listdir(path) if os.path.isfile(os.path.join(path, i))]
#Search for file
if "specific_file_I_want.json" in all_files:
print "FOUND FILE"
如果使用os.walk
:
all_files = [ files for root, _, files in os.walk(path) if os.path.abspath(root) == os.path.abspath(path) ][0]
if "specific_file_I_want.json" in all_files:
print "FOUND FILE"