Python中关于OS库的 *** 作

Python中关于OS库的 *** 作,第1张

开始表演:


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)

欢迎分享,转载请注明来源:内存溢出

原文地址:https://54852.com/langs/866825.html

(0)
打赏 微信扫一扫微信扫一扫 支付宝扫一扫支付宝扫一扫
上一篇 2022-05-12
下一篇2022-05-12

发表评论

登录后才能评论

评论列表(0条)

    保存