政府网站建设问题分析百度权重是怎么来的
文章目录
- 前言
- 1 读写txt
- 2 读写xml文件
- 3 读写json文件
- 4 命名/拷贝移动文件
- 总结
前言
本篇博文主要记录一些常见的文件读取操作,不定期更新扩充。
1 读写txt
import os
# 读
def read_txt(path):with open(path,'r') as f:while True:line = f.readline() # 读取整行数据if not line:breakimgsets.append(line.strip()) # 必须放在 if 之后,否则会多读入一个空字符。# 或者lines = f.readlines()for line in lines:imgsets.append(line.strip())#f.close() # f.close不用加,因为Python自动默认将操作系统的待写入的文件写到了磁盘里面。
# 写
def write_txt(path):with open(path,'w') as f:f.write('wulele\n')#f.close() # 和上面同理,with方法保证了 操作系统自动将文件完全写入磁盘了。
if __name__ == '__main__':# readread_path = '/home/wujian/MMLAB/gallery_content.txt'read_txt(read_path)# writewrite_path = '/home/wujian/MMLAB/save.txt'write_txt(write_path)
2 读写xml文件
import xml.etree.ElementTree as ET
def save_to_new_annotations(img,path):doc = ET.parse(path)root = doc.getroot()width,height,_ = img.shapefor size in root.findall('size'):size.find('width').text = str(width)size.find('height').text = str(height)f = 'E:/RotateVocDataset/VOCdevkit/VOC2007/NewAnnotations/000005.xml'doc.write(f,encoding="utf-8") #重新写入参数文件print('Done!')def read_annotation(path):root = ET.parse(path).getroot()sizes = []filename = root.find('filename').text # text后无括号# 获取图像的尺寸for size in root.findall('size'):width = size.find('width').textheight = size.find('height').textchannel = size.find('depth').textsizes.extend([width,height,channel])# 获取物体信息imdbs = []for obj in root.findall('object'):imdb = []label = obj.find('name').textbbox = obj.find('bndbox') # 由于bndbox非叶子节点,所以不能直接.textxmin = bbox.find('xmin').text # 获取bbox的信息ymin = bbox.find('ymin').textxmax = bbox.find('xmax').textymax = bbox.find('ymax').textimdb.extend([xmin,ymin,xmax,ymax,label])imdbs.append(imdb)return sizes,imdbsif __name__ == '__main__':img_path= 'E://RotateVocDataset/VOCdevkit/VOC2007/JPEGImages/000001.jpg'anno_path = 'E://RotateVocDataset/VOCdevkit/VOC2007/Annotations/000001.xml'img=cv2.imread(img_path)height, width ,_ = img.shapesize, imdbs = read_annotation(anno_path)print(size,'\n',imdbs)
3 读写json文件
json最大好处就是能够存储python的数据结构,即写进去是dict,读出来依旧是dict,所以大多数数据集都喜欢以json进行保存。而其中用到的主要api是:json.dumps(), json.loads()。
root_dir = '/mnt/data/VOC2017/train/'
sjs = root_dir + 'coco_hoi_train2017.json'
# 写入json
with open(sjs, 'w') as f:#f.write(str(annot) + '\n') # 写的方法会破坏python的数据结构f.write(json.dumps(content) + '\n') # json.dumps 就能保存python的数据结构
# 读取json
with open(json_path,'r') as f:lines = f.readlines()for line in lines:content = json.loads(line.strip())print(content['img'], content['label'])break
4 命名/拷贝移动文件
filename.zfill(6) # 字符串填充6位,右对齐。shutile.copyfile
总结
没啥可总结的…