遍历文件
- 1 遍历文件并读取
- 1.1 用os.path.join连接
- 1.2 用加号连接
- 1.3 遍历文件夹和文件
- 2 只读取指定格式的文件
- 3 文件的其它操作
- 3.1 获取文件路径里的文件名、后缀名和所在的文件夹
- 3.2 获取文件夹下的文件夹的文件
- 3.3 获取文件夹下的所有文件和文件夹
- 3.4 得到当前python文件的执行绝对路径
- 3.5 获取当前时间和运行时间
- 4 复制一个文件到另一个文件
- 4.1 文件的裁剪与复制
- 5 判断文件是否存在和创建
- 6 os进行文件操作
1 遍历文件并读取
1.1 用os.path.join连接
# 遍历文件夹里面的所有文件
import os
path = r'G:\zhongxian\统计的图片'
filenames = os.listdir(path)
print(filenames)
print(len(filenames))
for filename in filenames:
# 输出文件名
print(filename)
# 输出完整路径
print(os.path.join(path, filename))
1.2 用加号连接
# 进行png图像3通道到单通道的转换
import os
import cv2
path_img = 'D:/schoolWork/yaoganDetect/dataset/target/SegmentationClassPNG/'
img_dir = os.listdir(path_img)
# 批量处理
for img_name in img_dir:
img = cv2.imread(path_img + img_name)
blue, green, red = cv2.split(img)
save_path = "D:/schoolWork/yaoganDetect/presDataset/singlechaPNG/"+img_name
cv2.imwrite(save_path, red) # 写入图像
print("ok")
1.3 遍历文件夹和文件
2 只读取指定格式的文件
images = glob.glob(r'G:\XiaoMa\08OwnWork\zhongxian\语义分割数据\target\JPEGImages\*.jpg')
3 文件的其它操作
3.1 获取文件路径里的文件名、后缀名和所在的文件夹
# 获取文件名
dict_f['file_name'] = fname.split('/')[-1]
获取文件路径
images = r'G:\XiaoMa\08OwnWork\zhongxian\语义分割数据\target\JPEGImages\123.jpg'
kk = images.split("\\")[-1]
kk
s = images.replace(kk,'') # 删除即把对应字符替换为空
s
直接用os库
import os
img_path = r'E:\rs\2008\wenchuan_proj.tif'
os.path.dirname(img_path)
os.path.basename(img_path)
# 获取不带后缀的文件名和后缀名
import os
pathname = "../LR/ttnew/airplane1.tif"
basename = os.path.basename(pathname)
print("basename:"+basename)
splittext = os.path.splitext(basename)
print(splittext)
wenjianming = os.path.splitext(basename)[0]
houzhuiming = os.path.splitext(basename)[1]
print(wenjianming)
print(houzhuiming)
3.2 获取文件夹下的文件夹的文件
os.listdir()函数得到的是仅当前路径下的文件名,不包括子目录中的文件,所有需要使用递归的方法得到全部文件名。
直接给出代码,函数将返回类型为‘.jpeg’个文件名:
import os
def listdir(path, list_name):
for file in os.listdir(path):
file_path = os.path.join(path, file)
if os.path.isdir(file_path):
listdir(file_path, list_name)
elif os.path.splitext(file_path)[1]=='.jpeg':
list_name.append(file_path)
3.3 获取文件夹下的所有文件和文件夹
import os
def file_name(file_dir):
for root, dirs, files in os.walk(file_dir):
print(root) #当前目录路径
print(dirs) #当前路径下所有子目录
print(files) #当前路径下所有非目录子文件
3.4 得到当前python文件的执行绝对路径
python获取程序执行文件路径的方法(推荐)_python_脚本之家
https://www.jb51.net/article/138980.htm
import os
import sys
import time
dirname, filename = os.path.split(os.path.abspath(sys.argv[0])) # 获取绝对路径并把文件夹和文件名拆开
print(dirname) # G:\XiaoMa\semiSupervise\AdversarialSemanticSegmentationKeras-master\xiaoma
print(filename) # trrrr.py
print(os.path.realpath(sys.argv[0])) # G:\XiaoMa\semiSupervise\AdversarialSemanticSegmentationKeras-master\xiaoma\trrrr.py
print(sys.argv[0]) # G:\XiaoMa\semiSupervise\AdversarialSemanticSegmentationKeras-master\xiaoma\trrrr.py
print(os.getcwd()) # G:\XiaoMa\semiSupervise\AdversarialSemanticSegmentationKeras-master\xiaoma
print(__file__) # G:/XiaoMa/semiSupervise/AdversarialSemanticSegmentationKeras-master/xiaoma/trrrr.py
3.5 获取当前时间和运行时间
Python获取当前日期和日期差计算 - 云+社区 - 腾讯云
https://cloud.tencent.com/developer/article/1577646
import time
strtime = time.strftime('%Y-%m-%d %H:%M:%S',time.localtime())
print(strtime) # 2021-12-29 11:32:24
# 开始计时
time_start=time.time()
# 时间截止
time_end=time.time()
print('totally cost',time_end-time_start)
4 复制一个文件到另一个文件
def backup_file(path, path_two):
"""
:param path: 路径1
:param path_two: 路径2
:return:
"""
if os.path.isdir(path) and os.path.isdir(path_two): # 判断传入的值为文件夹
a = os.listdir(path) # 读取该路径下的文件为列表
for i in a:
po = os.path.join(path, i) # 路径1拼接
po_two = os.path.join(path_two, i) # 路径2拼接
with open(po, "rb") as f:
res_one = f.read()
with open(po_two, "wb") as a:
a.write(res_one)
print("{}复制成功".format(i))
else:
print("不是文件夹")
4.1 文件的裁剪与复制
# 实现文件的裁剪和复制
import cv2 as cv
import os
import gdal
import numpy as np
def jian(jpg_path,jpg_to_path,png_path,png_to_path):
"""
实现tif转jpg
:param tif_path:输入路径
:param jpg_path:输出路径
:return:
"""
filenames = os.listdir(jpg_path)
print(filenames)
print(len(filenames))
index = np.random.permutation(len(filenames))
filenames = np.array(filenames)[index].tolist()
print(filenames)
i = 0
for filename in filenames:
# 1 拷贝标签
i += 1
# 裁剪150个
if i>150:
break
file_path = os.path.join(jpg_path, filename)
jpg_to = os.path.join(jpg_to_path, filename) # 路径2拼接
with open(file_path, "rb") as f:
res_one = f.read()
with open(jpg_to, "wb") as a:
a.write(res_one)
# 拷贝标签
filename_label = filename[:-4]+".png"
file_png_path = os.path.join(png_path, filename_label)
png_to = os.path.join(png_to_path, filename_label) # 路径2拼接
with open(file_png_path, "rb") as f:
res_one = f.read()
with open(png_to, "wb") as a:
a.write(res_one)
os.remove(file_path)
os.remove(file_png_path)
def copy_file(jpg_path,jpg_to_path,png_path,png_to_path):
filenames = os.listdir(jpg_path)
print(filenames)
print(len(filenames))
index = np.random.permutation(len(filenames))
filenames = np.array(filenames)[index].tolist()
print(filenames)
i = 0
for filename in filenames:
# 1 拷贝标签
i += 1
if i > 200:
break
file_path = os.path.join(jpg_path, filename)
jpg_to = os.path.join(jpg_to_path, filename) # 路径2拼接
with open(file_path, "rb") as f:
res_one = f.read()
with open(jpg_to, "wb") as a:
a.write(res_one)
# 拷贝标签
filename_label = filename[:-4] + ".png"
file_png_path = os.path.join(png_path, filename_label)
png_to = os.path.join(png_to_path, filename_label) # 路径2拼接
with open(file_png_path, "rb") as f:
res_one = f.read()
with open(png_to, "wb") as a:
a.write(res_one)
if __name__ == '__main__':
jian(
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\1train\1img",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\2val\1img",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\1train\2label",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\2val\2label"
)
copy_file(
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\1train\1img",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\2val\1img",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\1train\2label",
r"I:\5GF2\2biaozhu9jing20220107\3dataset\7datasetsuncangP_N\2val\2label"
)
5 判断文件是否存在和创建
if not os.path.exists("./images"):
os.makedirs("./images")
6 os进行文件操作
(8条消息) Python OS模块常用函数总结_hmxz2nn的博客-CSDN博客_os模块常用函数
python os.path模块常用方法详解