栏目分类:
子分类:
返回
名师互学网用户登录
快速导航关闭
当前搜索
当前分类
子分类
实用工具
热门搜索
名师互学网 > IT > 软件开发 > 后端开发 > Python

Python中关于OS库的操作

Python 更新时间: 发布时间: IT归档 最新发布 模块sitemap 名妆网 法律咨询 聚返吧 英语巴士网 伯小乐 网商动力

Python中关于OS库的操作

开始表演:

import os

# join 函数
Path1 = 'home'
Path2 = 'develop'
Path3 = 'code'

Path10 = Path1 + Path2 + Path3
Path20 = os.path.join(Path1,Path2,Path3)
# 输入结果:
# print('Path10',Path10)
# print('Path20',Path20)

# os.path.join() 将分离的部分合成一个整体
filename = os.path.join('/home/ubuntu/python_coding','split_func')


# dirname 函数
ls = os.path.dirname(__file__)
print(ls)
# 输入结果:当前的绝对路径

# exists 函数
os.path.exists('common/sss')
# print(ll)  # 返回布尔值 True False

# 联合应用
# 可以作为判定:
dir_name = "./images"
if not os.path.exists(dir_name):  # 如果不存在这个path文件
    os.makedirs(dir_name, exist_ok=True)  # 那就新增一个path文件:可以递归的创建多个文件夹

dir_name = "./images/imgs2"
if not os.path.exists(dir_name):  # 判断一个文件夹是否存在,如果不存在就新建它,如果已经存在就跳过
    os.mkdir(dir_name)

# os.path.split()返回文件的路径和文件名
(dirname, filename) = os.path.split('/home/ubuntu/python_coding/split_func/split_function.py')
print('dirname:', dirname)
print('filename:', filename)
# 输出为:
# dirname: /home/ubuntu/python_coding/split_func
# filename: split_function.py

# os.path.splitext() 将文件名和扩展名分开
(fname, fename) = os.path.splitext('/home/ubuntu/python_coding/split_func/split_function.py')
print('fname:', fname)
print('fename:', fename)
# 输出结果:
# fname: /home/ubuntu/python_coding/split_func/split_function
# fename: .py

# 有关于文件的操作类
import os
import json
class FileOperate:
    def writefile(self, file, file_type, file_text):
        if file_type in ('json', 'txt', 'csv'):
            filedir = os.path.dirname(file)
            if not os.path.exists(filedir):  # 如果不存在,那就新建一个文件
                os.makedirs(filedir)
            fileojb = open(file, 'a+', encoding='utf-8')
            fileojb.write(file_text + 'n')
            return fileojb

    def readfile(self, filepath, file_type):
        if file_type in "json":
            with open(filepath, 'r', encoding='UTF-8-sig') as f:
                json_file = json.load(f)
                return json_file
        if file_type in "txt":
            with open(filepath, 'r', encoding='UTF-8-sig') as f:
                return f

if __name__ == '__main__':
    from common.config import get_value
    get_path = get_value('file', 'file_path')
    timestr = datetime.datetime.now().strftime('%Y_%m_%d_%H_%M_%S')
    txt_title = "Step" + "Description" + "CaseResult"
    fileobj = FileOperate().writefile(get_path+timestr+".txt", 'txt', txt_title)
转载请注明:文章转载自 www.mshxw.com
本文地址:https://www.mshxw.com/it/844155.html
我们一直用心在做
关于我们 文章归档 网站地图 联系我们

版权所有 (c)2021-2022 MSHXW.COM

ICP备案号:晋ICP备2021003244-6号