首页 > 编程语言 >python学习 - 对目录操作和对文件操作的 实例代码

python学习 - 对目录操作和对文件操作的 实例代码

时间:2024-06-16 10:02:34浏览次数:16  
标签:dstfile srcfile python self 实例 path print 操作 os

# !/usr/bin/python
# -*- coding: UTF-8 -*-

import os
import os, shutil


class OperatingFile:
    def creatFile(self, path):
        f = file(path, "w+")
        f.close()

    def readFile(self, path):
        #方法一
        f = open("E:/aa.txt")
        line = f.readline()
        while line:
            print line
            line = f.readline()
        f.close()

        # 方法二
        for line2 in open(path):
            print line2

        # 方法三
        f2 = open(path, "r")
        lines = f2.readlines()
        for line3 in lines:
            print line3

    def writeFile(self, path):
        # 写入文件,会删除原文件内容,文件不存在将创建
        fo = open(path, "w")
        fo.write("www.runoob.com!\nVery good site!\n")
        fo.close()

        # 以二进制,追加写入
        fo = open(path, "ab+")
        fo.write("这里是追加写入!")
        fo.close()

    def updataFileNme(self, path):
        os.rename(path, "E:/bb.txt")

    def delFile(self, path):
        os.remove("E:/bb.txt")

    def mymovefile(self, srcfile, dstfile):
        if not os.path.isfile(srcfile):
            print "%s not exist!" % (srcfile)
        else:
            fpath, fname = os.path.split(dstfile) # 分离文件名和路径
            if not os.path.exists(fpath):
                os.makedirs(fpath) # 创建路径
                shutil.move(srcfile, dstfile) # 移动文件
                print "move %s -> %s" % (srcfile, dstfile)

    def mycopyfile(self, srcfile, dstfile):
        if not os.path.isfile(srcfile):
            print "%s not exist!" % (srcfile)
        else:
            fpath, fname = os.path.split(dstfile) # 分离文件名和路径
            if not os.path.exists(fpath):
                os.makedirs(fpath) # 创建路径
                shutil.copyfile(srcfile, dstfile) # 复制文件
                print "copy %s -> %s" % (srcfile, dstfile)

    def makedir(self,path):
        isExists = os.path.exists(path)

        if not isExists:
            os.makedirs(path)
            print path + u' 创建成功'
            return True
        else:
            print path + u' 目录已存在'
            return False

    def discern(self,path):
        for filename in os.listdir(path):
            print filename

    def main(self):
        path = "E:/aa.txt"

        # 创建文件
        self.creatFile(path)

        # 写入文件
        self.writeFile(path)

        # 读取文件
        self.readFile(path)

        # 重命名文件
        self.updataFileNme(path)

        # 删除文件
        self.delFile(path)

        # copy文件/移动文件
        srcfile="/aa/a.txt"
        dstfile="/aa/aa/copyAA.txt"
        self.mycopyfile(srcfile,dstfile)
        #移动
        dstfile = "/aa/aa/a.txt"
        self.mymovefile(srcfile,dstfile)

        #文件夹自动创建与识别
        self.makedir(path)
        #识别文件目录
        _path=u"/aa"
        self.discern(_path)


if __name__ == '__main__':
    operatingfile = OperatingFile()
    operatingfile.main()
#!/usr/bin/evn python
# -*- encoding: utf-8 -*-
import os
import tempfile


def mkdir(path):
    path = path.strip()
    path = path.rstrip("\\")  # 去除尾部 \ 符号

    # 判断路径是否存在
    # 存在 True
    # 不存在 False
    isExists = os.path.exists(path)
    # 判断结果
    if not isExists:
        # 如果不存在则创建目录
        # 创建目录操作函数
        os.makedirs(path)
        print path + u' 创建成功'
        return True
    else:
        # 如果目录存在则不创建,并提示目录已存在
        print path + u' 目录已存在'
        return False


# 定义要创建的目录
mkpath = u"E:/test/one/6月"
# 调用函数
mkdir(mkpath)

tempPath = tempfile.gettempdir()                       # 获得系统临时文件路径
modernFilePath = os.path.realpath(__file__)           # 获得当前脚本所在目录
filename = os.path.basename(modernFilePath)          # 获得文件名
filepath = os.path.dirname(modernFilePath)          # 文件路径
extensionName = os.path.splitext(modernFilePath)[1]# 获得扩展名(后缀)

标签:dstfile,srcfile,python,self,实例,path,print,操作,os
From: https://blog.csdn.net/weixin_tank88921/article/details/139598875

相关文章

  • python学习 - for循环 各种使用技巧 案例代码
    #!/usr/bin/python#-*-coding:UTF-8-*-forletterin'Python':#第一个实例print'当前字母:',letterfruits=['banana','apple','mango']forfruitinfruits:#第二个实例print'当前水果:',fr......
  • python学习 - 对list列表的操作 实例代码
    #!/usr/bin/evnpython#-*-encoding:utf-8-*-list=[1,4,3,3,"A","B","c","A"]#增加list.append("AA")#像末尾增加一个新元素list.insert(1,"B")#像指定索引位置插入元素list.extend(["D","DD"])#新......
  • python学习 - 读取xls文件的操作案例代码
    #!/usr/bin/evnpython#-*-encoding:utf-8-*-importxlrdimportxlwtimportxlutils.copyclassExcels:defcreateExcel(self):workbook=xlwt.Workbook()sheet=workbook.add_sheet(u"sheet页名称",cell_overwrite_ok=True)......
  • python学习 - 操作redis数据库常用指令 案例
    #-*-coding:UTF-8-*-importredisimporttimeclassTestRedis:def__init__(self):self.dbconn=NonedefopenRedis(self):#连接redis,加上decode_responses=True,写入的键值对中的value为str类型,不加这个参数写入的则为字节类型。......
  • linux下C语言如何操作文件(二)
    上篇文章中,我们简单介绍了file_util.h中定义的各函数,今天我们来讲解如何实现头文件中定义的各函数。首先,在file_util.c中,我们需要引入相应的头文件:#include<stdio.h>#include<stdlib.h>#include<stdbool.h>#include<unistd.h>#include<sys/stat.h>#include<sys/typ......
  • 西门子学习笔记15 - 位逻辑操作的学习
    1、点动操作(按下按钮就启动松开就停止)2、自锁电路(可以自己保持的状态除非常闭停止按下)3、取反操作(顾名思义就是反过来1就变成0,0就变成1)4、置为复位(置位之后如果不复位的话就会一直为1)5、区域置位和复位(从起始的位开始的5个位被全部置为1或者全部复位为0)6、单个条件的......
  • 怎么把Python脚本打包成可执行程序exe文件?
    需求分析最近根据用户提的需求用python做了一个小工具,但是在给客户使用的时候不能直接发送python文件,毕竟让客户去安装python环境,那就离了大谱了。所以这时候就需要把多个py文件带着运行环境打包成EXE可执行文件。技术实现这里以window为例,Mac是同样的道理。一、检测脚......
  • python入门级经典交互式小程序
    今天学习做一个简单的交互式小程序知识点:1.对空列表进行添加元素,并分别打印每次添加的元素2.给while设置参数法进行循环3.for循环结合range()进行循环代码如下:klist=[]name=input("请输入你喜欢的明星:")while(name):  klist.append(name)  name=input......
  • 2024华为OD机试真题-堆内存申请-(C++/Python)-C卷D卷-100分
    2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++)题目描述有一个总空间为100字节的堆,现要从中新申请一块内存,内存分配原则为:优先紧接着前一块已使用内存,分配空间足够且最接近申请大小的空闲内存。输入描述第1行是1个整数,表示期望申请的内存字节数第2到第N行是用空格......
  • 2024华为OD机试真题-围棋的气-(C++/Python)-C卷D卷-100分
     2024华为OD机试题库-(C卷+D卷)-(JAVA、Python、C++) 题目描述围棋棋盘由纵横各19条线垂直相交组成,棋盘上一共19x19=361个交点,对弈双方一方执白棋,一方执黑棋,落子时只能将棋子置于交点上。“气”是围棋中很重要的一个概念,某个棋子有几口气,是指其上下左右方向四个相......