文件管理
查看文件夹下所有子目录及文件
参考:Python os.walk() 方法
也可以看我的这篇文章:【Python学习】读取文件夹下的所有文件
例子:
import os
for root, dirs, files in os.walk(".", topdown=False):
for name in files:
print(os.path.join(root, name))
for name in dirs:
print(os.path.join(root, name))
输出结果为
./.bash_logout
./amrood.tar.gz
./.emacs
./httpd.conf
./www.tar.gz
./mysql.tar.gz
./test.py
./.bashrc
./.bash_history
./.bash_profile
./tmp
./tmp/test.py
例子:
遍历”Day1-homework”目录下文件;
找到文件名包含“2020”的文件;
将文件名保存到数组result中;
按照序号、文件名分行打印输出。
#导入OS模块
import os
#待搜索的目录路径
path = "Day1-homework"
#待搜索的名称
filename = "2020"
#定义保存结果的数组
result = []
def findfiles():
#在这里写下您的查找文件代码吧!
i=0
for root, dirs, files in os.walk(path, topdown=True):
for name in files:
fileName=os.path.join(root,name)
if filename in fileName:
i+=1
# print("[{}],{}".format(i,fileName))
temp=[i,fileName]
result.append(temp)
# print(result)
for file_ in (result):
print(file_)
if __name__ == '__main__':
findfiles()
输出:
[1, 'Day1-homework/18/182020.doc']
[2, 'Day1-homework/4/22/04:22:2020.txt']
[3, 'Day1-homework/26/26/new2020.txt']