在学习深度学习理论的时候,因为缺少一些python基础知识,当自己独立编程时,会遇到一定困难,所以整理了一些可能遇到问题的知识点,希望可以帮助大家更好的进行编程。
文件读取
在进行项目编程时,常常会遇到读取文件的情况,那么如何读取文件呢?
函数 | 作用 |
---|---|
os.listdir(path) | 已知文件夹名,读取文件夹内文件名列表 |
os.path.join(self.image_dir, image_filename) | 文件名拼接 |
os.path.splitext(image_filename) | 文件名分割(内容+后缀) |
os.path.exists(label_path) | 判断文件是否存在 |
代码示例
已知文件夹名,读取文件夹内文件
利用 os 库下面的 listdir 函数进行文件夹下的文件遍历。
python
import os
path='data/archive/PlantDisease416x416/PlantDisease416x416/test'
i=0
for filename in os.listdir(path):
if filename.endswith('.jpg'):
print(filename)
i+=1
if i>=10:
break
输出结果
js
testImage416_60.jpg
testImage416_74.jpg
testImage416_48.jpg
testImage416_129.jpg
testImage416_101.jpg
testImage416_115.jpg
testImage416_114.jpg
testImage416_100.jpg
testImage416_128.jpg
testImage416_49.jpg
文件名分割
python
import os
path='data/archive/PlantDisease416x416/PlantDisease416x416/test'
i=0
for filename in os.listdir(path):
label_filename = os.path.splitext(filename)
print(label_filename)
i+=1
if i>=10:
break
输出结果
python
('testImage416_60', '.jpg')
('testImage416_74', '.jpg')
('testImage416_48', '.jpg')
('testImage416_201', '.txt')
('testImage416_215', '.txt')
('testImage416_129', '.jpg')
('testImage416_101', '.jpg')
('testImage416_115', '.jpg')
('testImage416_229', '.txt')
('testImage416_188', '.txt')