文件有关操作
1.写文件
f = open('model_data/test1.txt', 'r+') ##以写的方式打开文件
file = open('model_data/test1.txt', 'w').close()##清空文件中的内容
f.write(name+'\n')##写入内容
f.read()##有read写文件后可以书写下一行,不会覆盖
f.close()##文件close才保存
2.读文件:
并且按逗号解析数据
import os
image_name_path = os.path.expanduser(path)#linux下面,用系统,用~来代表"/home/你的名字/"这个路径的,而expanduser展开~
with open(image_name_path) as f:#打开文件
while True:
name1 = f.readline()#按行读数据
if not name1:
break ###如果读到最后一行退出
b = name1.split(',')#用split可以解析数据,,表示按空格解析['2','134','14\n']
b = [int(c.strip()) for c in b]#用这个语句可以将列表中元素直接去掉回车空格,并将字符串转换为数字[2,134,14]
anchor.append(b)#可以变成存储列表的列表
3.遍历文件夹下所有文件
import os
import random
import shutil
from glob import glob
def bianLi(src_dir,dst_dir):
for root,dirs,files in os.walk(src_dir):
for file in files:
print("open "+os.path.join(root,file))
if os.path.exists(src_dir + "/" + os.path.splitext(file)[0]+'.jpg') and os.path.exists(src_dir + "/" + os.path.splitext(file)[0]+'.xml'):
if os.path.splitext(file)[1] == '.xml':
##------------------------
# 添加对文件的操作
#-------------------------
for dir in dirs:
bianLi(src_dir + "/" + dir, dst_dir)
break
4.复制文件
def mycopyfile(srcfile, dstpath): # 复制函数
if not os.path.isfile(srcfile):
print("%s not exist!" % (srcfile))
else:
fpath, fname = os.path.split(srcfile) # 分离文件名和路径
if not os.path.exists(dstpath):
os.makedirs(dstpath) # 创建路径
shutil.copy(srcfile, dstpath + fname) # 复制文件
print("copy %s -> %s" % (srcfile, dstpath + fname))