亚洲乱码中文字幕综合,中国熟女仑乱hd,亚洲精品乱拍国产一区二区三区,一本大道卡一卡二卡三乱码全集资源,又粗又黄又硬又爽的免费视频

Python實現(xiàn)讀取文件夾按數(shù)字排序功能

 更新時間:2022年09月20日 14:24:24   作者:慕塵  
這篇文章主要介紹了Python讀取文件夾按數(shù)字排序,代碼簡單易懂,對大家的學(xué)習(xí)或工作具有一定的參考借鑒價值,需要的朋友可以參考下

先給大家介紹下Python讀取文件夾按數(shù)字排序的代碼,內(nèi)容如下所示:

python中 os.listdir()方法用于返回指定的文件夾包含的文件或文件夾的名字的列表

import os
path = "../data/materials/test/"
path_list = os.listdir(path)
print(path_list)

輸出

['1.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg', '15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '2.jpg', '20.jpg', '3.jpg','4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg']

返回的文件名不是順序的

使用sort()對返回的文件名列表進行排序

path = "../data/materials/test/"
path_list = os.listdir(path)
path_list.sort(key=lambda x: int(x.split('.')[0]))
print(path_list)

輸出

['1.jpg', '2.jpg', '3.jpg', '4.jpg', '5.jpg', '6.jpg', '7.jpg', '8.jpg', '9.jpg', '10.jpg', '11.jpg', '12.jpg', '13.jpg', '14.jpg', '15.jpg', '16.jpg', '17.jpg', '18.jpg', '19.jpg', '20.jpg']

擴展知識:

python讀取文件夾內(nèi)容

1. 文件夾讀取文件

Python os.listdir() 方法:

os.listdir() 方法用于返回指定的文件夾包含的文件或文件夾的名字的列表

import os, sys
# 打開文件
COOKED_FOLDER = './cooked_traces/' ?#文件夾的地址
dirs = os.listdir( COOKED_FOLDER )
?
# 輸出所有文件和文件夾
for file in dirs:
? ?print (file) ? ? ? ? ? ? #讀出所有文件夾名字

2. 文件中讀取文件內(nèi)容

open() 方法

open(file, moopen(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None, closefd=True, opener=None)

https://www.runoob.com/python/file-methods.html   #具體的每個關(guān)鍵字的含義

Python open() 方法用于打開一個文件,并返回文件對象,在對文件進行處理過程都需要使用到這個函數(shù),如果該文件無法被打開,會拋出 OSError。

import os, sys?
# 打開文件
COOKED_FOLDER = './cooked_traces/' ?#文件夾的地址
dirs = os.listdir( COOKED_FOLDER )
?
# 輸出所有文件和文件夾
for file in dirs:
# ? print(file) ?#輸出所有文件夾名字
? ?filepath = COOKED_FOLDER + file ?#文件所在地址
? ?with open(filepath,'r') as f: ? ?#讀取文件
? ? ? ? for line in f : ?# ? ? ? ? ?#按行遍歷文件內(nèi)容
? ? ? ? ? ? print(line) ?#輸出每行信息

到此這篇關(guān)于Python讀取文件夾按數(shù)字排序的文章就介紹到這了,更多相關(guān)Python文件夾按數(shù)字排序內(nèi)容請搜索腳本之家以前的文章或繼續(xù)瀏覽下面的相關(guān)文章希望大家以后多多支持腳本之家!

相關(guān)文章

最新評論