python - Python如何遍历文件目录让程序知道如何遍历到最后一个文件
问题描述
Python如何遍历文件目录,让程序知道要遍历到最后一个文件?我已经尽力了。这不好。一个目录下有几个文件夹,每个文件夹有几十个子文件夹,每个文件夹有两个文件。我只能非常严格地识别最后一个文件。
def openfile(inputdir):
global total,namebefor,nameafter,array
file = os.listdir(inputdir)
for fi in file:
fidir = os.path.join(inputdir, fi)
if os.path.isfile(fidir) and os.path.splitext(fidir)[1] in [".CSV"]:
news = fidir.split("\\")
nowname = news[-3]
namebefor = nowname
if namebefor == nowname:
if namebefor !=nameafter:
if nameafter != namebefor and array!=[]:
print(nameafter)
print(array)
print(int(total / 2))
array = []
total = 0
else:
array.append(fidir)
total = total+1
else:
array.append(fidir)
total = total + 1
if nameafter == namebefor and array[-1].split("\\")[-1] == "9.CSV":
print(array)
print(nameafter)
print(int(total / 2))
array = []
total = 0
nameafter = nowname
elif os.path.isdir(fidir):
openfile(fidir)
如果我不使用 "and array [-1].split("\") [-1]="9.CSV":" 在这种情况下,就无法打印出 YD-4 的路径。但是太死板了。如果我的最后一个不是 9.CSV,我必须不断更改条件。
解决方案
enter code hereafor dirpath, dirnames, filenames in os.walk(".."):
for filepath in filenames:
if os.path.splitext(os.path.join(dirpath, filepath))[1] in [".CSV"]:
nowpath = os.path.join(dirpath, filepath)
total += 1
nowname =dirpath.split("\\")[-2]
namebefor=nowname
if namebefor==nowname:
if nameafter!=namebefor:
if namebefor!=nameafter and array!=[]:
print("%s" % array)
array = []
total = 0
array.append(nowpath)
total += 1
else:
array.append(nowpath)
else:
array.append(nowpath)
nameafter=nowname
# print(os.path.splitext(os.path.join(dirpath, filepath))[0])
# print(os.path.join(dirpath, filepath))
推荐阅读
- python - 使用 pyinstaller 将 .py 转换为 .exe 后缺少模块
- c++ - QTcpSocket:通信数小时后服务器响应延迟
- r - 为什么在 R 中使用管道运算符会出现以下错误?
- express - cookie 中的 Express Gateway JWT 验证
- asp.net-mvc - 如何在.Net Core 2.2中通过ajax调用处理AutoValidateAntiForgeryToken
- css - 为什么 safari 有时无法快速响应 CSS?
- path - 邮递员从 csv 数据文件中读取。每次迭代都需要新的 url
- python - 将csv转换为json多文档?
- c++ - 纯虚方法调用 terminate 调用时没有活动异常 当函数执行时,它返回
- angular - 当主/详细信息处于活动状态并且至少有一行扩展到其详细信息时,Ag-grid 更新数据失败