PYTHON文件有关操作

文件有关操作
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))
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值