操作文件的一些python方法总结(特别基础)

# encoding=utf-8
import os


class FileTools(object):

    @staticmethod
    def get_abs_path(path):
        """
        获取文件绝对路径
        :param path: 输入的是相对路径/类似于 ~ 这种路径
        :return: 返回绝对路径,但是路径真实性,不一定
        """
        return os.path.abspath(os.path.expanduser(path))

    def make_path(self, path, file_=False):
        """
        根据输入的路径创建文件夹或者文件
        :param path: 输入的路径(支持相对路径)
        :param file_: True:想要创建文件, False:创建文件夹
        :return:
        """
        abs_path = self.get_abs_path(path)
        if not file_ and not os.path.exists(abs_path):
            os.makedirs(abs_path)
            return True
        elif file_ and os.path.exists(abs_path) and os.path.isdir(abs_path):
            raise Exception("[{}] is a dir and it already exists".format(abs_path))
        elif file_ and not os.path.exists(abs_path):
            with open(abs_path, "w"):
                return True
        else:
            return True

    def get_dir_files(self, dir_path, get_all=False):
        """
        遍历文件夹下的所有文件
        :param dir_path:
        :return:
        """
        abs_path = self.get_abs_path(dir_path)
        all_dir_list = []
        all_file_list = []
        root_1 = ""
        for root, dirs, files in os.walk(abs_path):
            # root 表示当前正在访问的文件夹路径
            # dirs 表示该文件夹下的子目录名list
            # files 表示该文件夹下的文件list
            if not get_all and root == abs_path:
                return root, [os.path.join(root, dir) for dir in dirs], [os.path.join(root, file) for file in files]
            root_1 = root if not root_1 else root_1
            all_dir_list.extend([os.path.join(root, dir) for dir in dirs])
            all_file_list.extend([os.path.join(root, file) for file in files])
        return root_1, all_dir_list, all_file_list


if __name__ == '__main__':
    file_tools = FileTools()


Python 面试100讲(基于Python3.x)

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值