【发布时间】:2021-10-11 11:53:11
【问题描述】:
我想使用 for 循环和 os.listdir() 遍历文件夹,我只是想知道在括号中写入什么来访问特定文件。谢谢!
【问题讨论】:
-
os.listdir(路径)
我想使用 for 循环和 os.listdir() 遍历文件夹,我只是想知道在括号中写入什么来访问特定文件。谢谢!
【问题讨论】:
以下示例应该对您有所帮助:
import os
path = "C:/Users/TestDir"
dirs = os.listdir( path )
for file in dirs:
print(file)
【讨论】:
你可以很容易地用谷歌搜索。 https://www.tutorialspoint.com/python/os_listdir.htm 您只需要括号中的路径。
【讨论】:
根据我的理解,您想遍历特定文件夹中的文件,直到找到一个特定文件?你可以这样做:
import os
FileToBeFound = "Your File Name To Find"
path = "Path to the directory you would like to check for a file in"
for file in os.listdir(path):
if file == FileToBeFound:
#do stuff with file
break
else:
continue
【讨论】: