Python遍歷資料夾下所有檔案

2021-09-13 14:26:01 字數 1986 閱讀 9162

7只遍歷當前資料夾(不遞迴遍歷)

import glob

dir=

'test'

samples = glob.glob(

dir+

'/*'

)print

(samples)

print

(len

(samples)

)

['test\\1.txt', 'test\\new']

2

遍歷當前資料夾下所有的.txt

import glob

dir=

'test'

samples = glob.glob(

dir+

'/*.txt'

)print

(samples)

print

(len

(samples)

)

['test\\1.txt']

1

遍歷二級資料夾下所有的.txt

import glob

dir=

'test'

samples = glob.glob(

dir+

'/*/*.txt'

)print

(samples)

print

(len

(samples)

)

['test\\new\\2.txt', 'test\\new\\3.txt']

2

只要檔名

import os

import glob

dir=

'./test'

samples = glob.glob(

dir+

'/**'

, recursive=

true

)del samples[0]

samples =

list

(map

(os.path.basename, samples)

)print

(samples)

print

(len

(samples)

)

不呼叫庫

dir

='./test'

for file_path in os.listdir(

dir)

:if file_path.endswith(

".txt"):

file_path = os.path.join(

dir, file_path)

print

(os.path.basename(file_path)

.rstrip(

".txt"

))

python之glob模組以及根據路徑獲取檔案

遍歷資料夾下所有檔案

對於遍歷資料夾來說,其實並不麻煩,使用file轉化位址物件,再用file組獲取內容,其實google都差不多做好了,我就懶得廢話了,直接上 public listlist new arraylist 遍歷所有檔案 public listgetfilelist string path else ret...

python遍歷資料夾下的所有檔案

在python中我們一般使用os模組來操作資料夾或檔案,os為python的內建模組,使用時直接匯入即可 import os當目標資料夾中只有檔案時,我們使用os模組的listdir 方法即可 該方法可以返回目標路徑下的檔案和資料夾的名字列表,引數就是目標路徑。荔枝 檔案結構如下 def getfi...

python 遍歷資料夾下的所有檔案

基礎 import os 遍歷資料夾 def walkfile file for root,dirs,files in os.walk file root 表示當前正在訪問的資料夾路徑 dirs 表示該資料夾下的子目錄名list files 表示該資料夾下的檔案list 遍歷檔案 for f in ...