python經(jīng)典實(shí)例—遍歷文件夾和文件
提問(wèn)人:楊紫紅發(fā)布時(shí)間:2020-11-26
import os
import os.path
# os,os.path里包含大多數(shù)文件訪問(wèn)的函數(shù),所以要先引入它們.
# 請(qǐng)按照你的實(shí)際情況修改這個(gè)路徑
rootdir = " d:/download "
for parent, dirnames, filenames in os.walk(rootdir):
# case 1:
for dirname in dirnames:
print ( " parent is: " + parent)
print ( " dirname is: " + dirname)
# case 2
for filename in filenames:
print ( " parent is: " + parent)
print ( " filename with full path : " + os.path.join(parent, filename))
''' 知識(shí)點(diǎn):
* os.walk返回一個(gè)三元組.其中dirnames是所有文件夾名字(不包含路徑),filenames是所有文件的名字(不包含路徑).parent表示父目錄.
* case1 演示了如何遍歷所有目錄.
* case2 演示了如何遍歷所有文件.
* os.path.join(dirname,filename) : 將形如"/a/b/c"和"d.java"變成/a/b/c/d.java".
'''
import os.path
# os,os.path里包含大多數(shù)文件訪問(wèn)的函數(shù),所以要先引入它們.
# 請(qǐng)按照你的實(shí)際情況修改這個(gè)路徑
rootdir = " d:/download "
for parent, dirnames, filenames in os.walk(rootdir):
# case 1:
for dirname in dirnames:
print ( " parent is: " + parent)
print ( " dirname is: " + dirname)
# case 2
for filename in filenames:
print ( " parent is: " + parent)
print ( " filename with full path : " + os.path.join(parent, filename))
''' 知識(shí)點(diǎn):
* os.walk返回一個(gè)三元組.其中dirnames是所有文件夾名字(不包含路徑),filenames是所有文件的名字(不包含路徑).parent表示父目錄.
* case1 演示了如何遍歷所有目錄.
* case2 演示了如何遍歷所有文件.
* os.path.join(dirname,filename) : 將形如"/a/b/c"和"d.java"變成/a/b/c/d.java".
'''
繼續(xù)查找其他問(wèn)題的答案?
相關(guān)視頻回答
點(diǎn)擊加載更多評(píng)論>>