當前位置:首頁 » 文件管理 » python歷遍文件夾

python歷遍文件夾

發布時間: 2022-04-20 16:50:45

① 用python遍歷一個文件夾下的文件給出兩個參數表示時間,如何挑選這兩個時間段之間的文件

listdir( path )列出當前path路徑下的所有文件
getctime( file ) 得到file的創建時間(秒),另外getmtime得到文件的修改
gmttime( seconds ) 把getctime得到的秒數轉換為一個gmtime結構體
datetime()構造日期函數,把gmtime結構體的內容穿進去,就得到了可比較時間的datetime對象
[ file for item,file in listdate if (starttime < item < endtime) ]
把滿足 starttime < item < endtime 條件的文件選取出來就可以了。

from time import gmttime
from datetime import datetime
from os.path import getctime
form os import listdir

def listdir(path, starttime, endtime ):
if not isinstance(starttime, datetime)
raise TypeError
if not isinstance(endtime, datetime)
raise TypeError
if starttime > endtime:
starttime, endtime = endtime, starttime
listtime = [ (gmtime(getctime(file)),file) for file in listdir( path ) ]
listdate = ([datetime( t.tm_year, t.tm_mon, t.tm_mday, t.tm_hour, t.tm_min, t.tm_sec ),file) for t, file in listtime]
return [ file for item,file in listdate if (starttime < item < endtime) ]

② 使用python遍歷文件夾將文件夾中所有的txt文本轉為html連接形式。

importos
defgetalltxtfilename(path):
txtfilenames=[]
fordirpath,dirnames,filenamesinos.walk(path):
filenames=filter(lambdafilename:filename[-4:]=='.txt',filenames)
filenames=map(lambdafilename:os.path.join(dirpath,filename),filenames)
txtfilenames.extend(filenames)
returntxtfilenames
deftxttohtmllink(path):
filenames=getalltxtfilename(path)
htmllink=[]
forfilenameinfilenames:
ifos.path.isfile(filename):
htmllinktext=''
myfile=open(filename)
firstline=myfile.readline()
whilefirstlineandlen(firstline)<2:
firstline=myfile.readline()
ifnotfirstline:
firstline=''*2
else:
firstline=firstline.strip(' ')
htmllinktext+=firstline[0]+'<ahref="'+
filename+'">'+
firstline[1:]+'</a><br>'
htmllink.append(htmllinktext)
myfile.close()
returnhtmllink
path=r"文件夾路徑"#將此處替換為實際文件夾的路徑
htmllinks=txttohtmllink(path)
forhtmllinkinhtmllinks:
printhtmllink

在html標記前加上一個字元,這就不是合法的html文本形式,還是按照要求做了,如果輸入到html文件肯定會出錯

③ python,如何遍歷一個目錄,輸出所有文件名

importos

defiterbrowse(path):
forhome,dirs,filesinos.walk(path):
forfilenameinfiles:
yieldos.path.join(home,filename)


forfullnameiniterbrowse("/home/bruce"):
printfullname

④ 如何利用Python遍歷文件夾

1. 基本實現

[root@localhost ~]# cat dirfile.py

import os
path='/tmp'for dirpath,dirnames,filenames in os.walk(path): for file in filenames:
fullpath=os.path.join(dirpath,file) print fullpath

執行結果如下:

[root@localhost ~]# python dirfile.py
/tmp/yum.log/tmp/pulse-3QSA3BbwpQ49/pid/tmp/pulse-3QSA3BbwpQ49/native/tmp/.esd-0/socket

2. 在上例的基礎上傳遞參數

import os,sys
path=sys.argv[1]for dirpath,dirnames,filenames in os.walk(path): for file in filenames:
fullpath=os.path.join(dirpath,file) print fullpath

執行方式為:[root@localhost ~]# python dirfile.py /tmp

在這里,sys.argv[1]是接受參數,也可以定義sys.argv[2]接受第二個參數

3. 如何用函數實現

PS:

1> def __init__():函數,也叫初始化函數。

self.path = path可以理解為初始化定義了1個變數。 在後面的def裡面調用的時候必須要使用self.path而不能使用path

2>__name__ == '__main__'

模塊是對象,並且所有的模塊都有一個內置屬性 __name__。一個模塊的 __name__ 的值取決於您如何應用模塊。如果 import 一個模塊,那麼模塊__name__ 的值通常為模塊文件名,不帶路徑或者文件擴展名。但是您也可以像一個標準的程序樣直接運行模塊,在這種情況下, __name__ 的值將是一個特別預設"__main__"。上述類中加上__name__ == '__main__'的判斷語句,可以直接在終端環境下執行python dirfile.py /tmp進行測試,不必非得在互動式環境下導入模塊進行測試。

⑤ 如何用Python實現目錄遍歷

1. 基本實現

[root@localhost ~]# cat dirfile.py

import os
path='/tmp'
for dirpath,dirnames,filenames in os.walk(path):
for file in filenames:
fullpath=os.path.join(dirpath,file)
print fullpath
執行結果如下:

[root@localhost ~]# python dirfile.py
/tmp/yum.log
/tmp/pulse-3QSA3BbwpQ49/pid
/tmp/pulse-3QSA3BbwpQ49/native
/tmp/.esd-0/socket

⑥ Python中如何遍歷指定目錄下的所有文件

例如:在C:\TDDOWNLOAD目錄下有a.txt、b.txt兩個文件,另有\sub1子文件夾,C:\TDDOWNLOAD\sub1下又有c.txt、d.txt兩個文件。

1. os.walk
os.walk()返回一個三元素的tuple:當前路徑、子文件夾名稱、文件列表。
>>> import os
>>> def fun( path ):
... for root, dirs, files in os.walk( path ):
... for fn in files:
... print root, fn
...
>>> fun( r'C:\TDDOWNLOAD' )
C:\TDDOWNLOAD a.txt
C:\TDDOWNLOAD b.txt
C:\TDDOWNLOAD\sub1 c.txt
C:\TDDOWNLOAD\sub1 d.txt
>>>

2. glob.glob
glob.glob()只接受一個參數,這個參數既代有路徑,又代有匹配模式,返回值為一個列表。注意,glob.glob()無法直接穿透子文件夾,需要自己處理:
>>> def fun( path ):
... for fn in glob.glob( path + os.sep + '*' ): # '*'代表匹配所有文件
... if os.path.isdir( fn ): # 如果結果為文件夾
... fun( fn ) # 遞歸
... else:
... print fn
...
>>> fun( r'C:\TDDOWNLOAD' )
C:\TDDOWNLOAD\a.txt
C:\TDDOWNLOAD\b.txt
C:\TDDOWNLOAD\sub1\c.txt
C:\TDDOWNLOAD\sub1\d.txt
>>>

'*'為匹配模式,代表匹配所有文件,只有這樣才能將子文件夾查出來,以便遞歸深入,探查下一層的文件。

⑦ 如何利用Python遍歷文件夾

import os
import os.path
rootdir = 「d:\data」 # 指明被遍歷的文件夾

for parent,dirnames,filenames in os.walk(rootdir): #三個參數:分別返回1.父目錄 2.所有文件夾名字(不含路徑) 3.所有文件名字
for dirname in dirnames: #輸出文件夾信息
print "parent is:" + parent
print "dirname is" + dirname

for filename in filenames: #輸出文件信息
print "parent is": + parent
print "filename is:" + filename
print "the full name of the file is:" + os.path.join(parent,filename) #輸出文件路徑信息

#windows下為:d:\data\query_text\EL_00154

⑧ 讀取python遍歷中文目錄得到的文件路徑報錯

這是因為路徑裡麵包含中文的原因:

  1. linux的系統字元編碼默認為utf-8,而要搜索的文件路徑nameFile是Unicode,需要進行解碼成unicode,因此作如下修改:

  2. fout=codecs.open(nameFile.encode("utf-8"),"w","utf-8"
  3. 當然,另外一種方法就是修改為英文的路徑;

  4. 關於編碼和解碼的知識,請參考:http://www.cnblogs.com/qiernonstop/p/3634462.html

⑨ python 遞歸遍歷文件夾

沒有仔細看,但你的第一句就有錯
def distinguish_file(user_paht):
參數應為user_path

⑩ 如何用python遍歷文件夾下的所有excel文件

大數據處理經常要用到一堆表格,然後需要把數據導入一個list中進行各種演算法分析,簡單講一下自己的做法:

1.如何讀取excel文件

網上的版本很多,在xlrd模塊基礎上,找到一些源碼

[python]view plain

  • importxdrlib,sys

  • importxlrd

  • defopen_excel(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx"):

  • data=xlrd.open_workbook(file)

  • returndata

  • #根據索引獲取Excel表格中的數據參數:file:Excel文件路徑colnameindex:表頭列名所在行的所以,by_index:表的索引

  • defexcel_table_byindex(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx",colnameindex=0,by_index=0):

  • data=open_excel(file)

  • table=data.sheets()[by_index]

  • nrows=table.nrows#行數

  • ncols=table.ncols#列數

  • colnames=table.row_values(colnameindex)#某一行數據

  • list=[]

  • forrownuminrange(1,nrows):

  • row=table.row_values(rownum)

  • ifrow:

  • app={}

  • foriinrange(len(colnames)):

  • app[colnames[i]]=row[i]

  • list.append(app)

  • returnlist

  • #根據名稱獲取Excel表格中的數據參數:file:Excel文件路徑colnameindex:表頭列名所在行的所以,by_name:Sheet1名稱

  • defexcel_table_byname(file="C:/Users/flyminer/Desktop/新建MicrosoftExcel工作表.xlsx",colnameindex=0,by_name=u'Sheet1'):

  • data=open_excel(file)

  • table=data.sheet_by_name(by_name)

  • nrows=table.nrows#行數

  • colnames=table.row_values(colnameindex)#某一行數據

  • list=[]

  • forrownuminrange(1,nrows):

  • row=table.row_values(rownum)

  • ifrow:

  • app={}

  • foriinrange(len(colnames)):

  • app[colnames[i]]=row[i]

  • list.append(app)

  • returnlist

  • defmain():

  • tables=excel_table_byindex()

  • forrowintables:

  • print(row)

  • tables=excel_table_byname()

  • forrowintables:

  • print(row)

  • if__name__=="__main__":

  • main()

  • 最後一句是重點,所以這里也給代碼人點個贊!
  • 最後一句讓代碼里的函數都可以被復用,簡單地說:假設文件名是a,在程序中import a以後,就可以用a.excel_table_byname()和a.excel_table_byindex()這兩個超級好用的函數了。

    2.然後是遍歷文件夾取得excel文件以及路徑:,原創代碼如下:

    [python]view plain

  • importos

  • importxlrd

  • importtest_wy

  • xpath="E:/唐偉捷/電力/電力系統總文件夾/舟山電力"

  • xtype="xlsx"

  • typedata=[]

  • name=[]

  • raw_data=[]

  • file_path=[]

  • defcollect_xls(list_collect,type1):

  • #取得列表中所有的type文件

  • foreach_elementinlist_collect:

  • ifisinstance(each_element,list):

  • collect_xls(each_element,type1)

  • elifeach_element.endswith(type1):

  • typedata.insert(0,each_element)

  • returntypedata

  • #讀取所有文件夾中的xls文件

  • defread_xls(path,type2):

  • #遍歷路徑文件夾

  • forfileinos.walk(path):

  • foreach_listinfile[2]:

  • file_path=file[0]+"/"+each_list

  • #os.walk()函數返回三個參數:路徑,子文件夾,路徑下的文件,利用字元串拼接file[0]和file[2]得到文件的路徑

  • name.insert(0,file_path)

  • all_xls=collect_xls(name,type2)

  • #遍歷所有type文件路徑並讀取數據

  • forevey_nameinall_xls:

  • xls_data=xlrd.open_workbook(evey_name)

  • foreach_sheetinxls_data.sheets():

  • sheet_data=test_wy.excel_table_byname(evey_name,0,each_sheet.name)

  • #請參考讀取excel文件的代碼

  • raw_data.insert(0,sheet_data)

  • print(each_sheet.name,":Datahasbeendone.")

  • returnraw_data

  • a=read_xls(xpath,xtype)

  • print("Victory")

  • 歡迎各種不一樣的想法~~


熱點內容
存儲過程異常 發布:2024-05-05 23:24:03 瀏覽:397
winxp訪問不了win7 發布:2024-05-05 23:05:23 瀏覽:733
演算法牛 發布:2024-05-05 22:43:40 瀏覽:719
grublinux引導 發布:2024-05-05 22:37:56 瀏覽:215
unix高級編程第三版pdf 發布:2024-05-05 22:32:09 瀏覽:958
手機wap網站源碼 發布:2024-05-05 22:27:44 瀏覽:259
python修改文件某一行 發布:2024-05-05 22:18:22 瀏覽:457
md5加密64 發布:2024-05-05 21:59:30 瀏覽:527
259pp頁面訪問升級 發布:2024-05-05 21:47:51 瀏覽:89
迅雷阻止上傳 發布:2024-05-05 21:26:19 瀏覽:914