Python回顾总结篇

版权声明:本文为博主原创文章,未经博主允许不得转载。 https://blog.csdn.net/qq_39591494/article/details/83089633

Python之管理目录与文件(个人总结)

一、什么是目录树?(总结)

目录树就相当于文件夹,路径就是一条字符串例如:/usr/local/src == “/usr/local/src” 路径还会分为相对路径和绝对路径

1.1、使用Jupyter notebook运行windows命令

以下环境为Jupyter notebook环境,运行Windows操作系统中的命令。

1.1.1、进入Windows的某个目录(使用%cd命令)

%cd F:\python_test1\Yankerp_test\result_test # 进入F:\python_test1\Yankerp_test\result_test目录中

1.1.2、查看当前的工作目录(使用%pwd命令)

在1.1.1中已经进入了F:xxx目录当中,在这里使用%pwd来查看当前的工作目录那么就是在:F:\python_test1\Yankerp_test\result_test

%pwd
>>> F:\python_test1\Yankerp_test\result_test # 输出结果

1.1.3、查看当前工作目录中有哪些文件或者目录(使用%ls命令)

说白了,就是查看当前的工作目录也就是F:\python_test1\Yankerp_test\result_test目录中有哪些数据(不管是文件还是文件夹)

%ls # 数据(忽略)

在Jupyter notebook对windows进行操作其实很简单,在之后我们会通过vscode或者Pycharm等工具进行对文件或者目录操作,那么以上介绍的是在Jupyter notebook中进行操作,肯定是不可以在vscode以及Pycharm等编辑器使用的,所以接下来会了解在Python中如何对文件和文件夹进行操作。

二、目录树==文件夹(总结)

接下来介绍几个方法 (非常重要!!!)

  • os.listdir()
  • os.getcwd()
  • os.chdir(’’)
  • os.mkdir()
  • os.path.exists()
  • os.path.isdir()

在以上的方法中好像看到有一个OS模块,在os.后面的就是os中的方法

2.1、什么是OS模块?

我们平时工作中很常用到的一个模块,通过os模块调用系统命令,获得路径,获取操作系统的类型等都是使用该模块。

2.2、导入os模块并使用

在使用os模块之前我们需要进行导入的一步操作

import os # 导入os模块
test_path = r"F:\python_test1\Yankerp_test" 
# 这个就是一个普通的变量而已,和name = "yankai"一个道理,前面的r代表原始的,让系统知道,我定义的是路径这么一个东西

2.2.1、如何查看当前目录下有什么数据?

使用os.listdir() 如下:

result = os.listdir(test_path) # 使用os.listdir方法来查看test_path目录中有哪些文件,赋值到result变量中
# test_path:这个是2.2中定义的windows目录路径

for i in result: # 使用for循环以此打印result中的列表内容
    print(i) # 输出即可
######## 以下为输出结果
>>>CardRes.dll
COMToolKit.dll
config.ini
CUQG.ocx
dbghelp.dll
Factory.dll
Factory2.dll
GameListMenu1.dll
GamePublic.dll
result_test

2.2.2、os.getcwd() 查看当前的工作目录

import os
os.getcwd()
>>> 'F:\\python_test1\\Yankerp_test'

2.2.3、os.chdir() # 切换目录

import os
os.chdir("result_test") # 切换路径

os.getcwd() # 查看当前的工作路径
>>>'F:\\python_test1\\Yankerp_test\\result_test'

2.2.4、os.mkdir() 创建目录

import os
os.getcwd()
>>>'F:\\python_test1\\Yankerp_test\\result_test'
os.mkdir("zhangsanlisi") # 在 'F:\\python_test1\\Yankerp_test\\result_test' 目录中在创建一个名字为:zhangsanlisi的目录

三、路径就是一条字符串(总结)

  • os.path.join()
  • os.path.exists()
  • os.path.isdir()

3.1、os.path.join()

os.path.join("c","d")
>>>'c\\d'

3.2、os.path.exists()

os.path.exists(r"F:\python_test1\Yankerp_test") # 判断是否存在某文件,如果存在,则告诉用户。否则写入数据
>>>True
os.path.exists(r"aaa") # 判断是否存在某文件,如果存在,则告诉用户。否则写入数据
>>>False

3.3、os.path.isdir()

os.path.isdir(r"F:\python_test1\Yankerp_test") # 判断是否是一个目录
>>>True
os.path.isdir(r"F:\python_test1\Yankerp_test\result_test\1.docx")  # 判断是否是一个目录
>>>False

二、命名管理(总结)

1、命名管理(路径的各级名称)

  • path.split(os.path.sep)
  • os.path.basename()
  • os.path.dirname()

2、删除文件

  • os.unlink
  • shutil.rmtree(path)

3、复制和移动 shutil

  • copy
  • copytree
  • move

1.1、path.split

import os
test_path = (r"F:\python_test1\Yankerp_test\result_test")
os.path.sep
>>>'\\'
test_path.split(os.path.sep)
>>>['F:', 'python_test1', 'Yankerp_test', 'result_test'] # 输出结果

1.2、os.path.splitext

os.path.splitext(test_path)
>>>('F:\\python_test1\\Yankerp_test\\result_test', '')
 
os.path.splitext(r"F:\python_test1\Yankerp_test\result_test\1.docx")
>>>('F:\\python_test1\\Yankerp_test\\result_test\\1', '.docx')
 
os.path.split(r"F:\python_test1\Yankerp_test\result_test\1.docx")
>>>('F:\\python_test1\\Yankerp_test\\result_test', '1.docx')

1.3、os.path.basename() && os.path.dirname()

test_path = (r"F:\python_test1\Yankerp_test\result_test")
 
os.path.basename(test_path)
>>>result_test
 
os.path.dirname(test_path)
>>>'F:\\python_test1\\Yankerp_test'

2.1、删除文件或目录

2.1.1、删除一个目录

import shutil
shutil.rmtree("zhangsan") # zhangsan为目录名

2.1.2、删除文件(1.docx)

os.getcwd()
>>>'F:\\python_test1\\Yankerp_test\\result_test'
 
os.listdir()
['1.docx',
 '1.jfif',
 '2-1G22QK950918.jpg',
 '2.pptx',
 '21.png',
 '2DEngineDll.dll',
 '3.png',
 '31.jpg',
 '4.jpg',
 'bugreport.exe',
 'CardRes.dll',
 'COMToolKit.dll',
 'config.ini',
 'CUQG.ocx',
 'dbghelp.dll',
 'Factory.dll',
 'Factory2.dll',
 'GameListMenu1.dll',
 'GamePublic.dll',
 'GdiPlus.dll',
 'hcq.dll',
 'HelpDll.dll',
 'ImageOle.dll',
 'ItemDisp.dll',
 'navicatformysql.zip',
 'robomongo-1.0.0-windows-x86_64-89f24ea.rar',
 'securcrt.pc141.com.rar',
 'tt.sh',
 'zhangsan',
 'zhangsan_test.pptx',
 '啊.png',
 '新建 WinRAR 压缩文件.rar']

os.unlink(“1.docx”) # 删除1.docx文件
2.1.3、复制,移动(21.png)

import shutil
shutil.copy("21.png","2121.png")
os.listdir()
['1.jfif',
 '2-1G22QK950918.jpg',
 '2.pptx',
 '21.png',
 '2121.png',
 '2DEngineDll.dll',]

2.1.4、移动

shutil.move("3.png","3131.png")

实例1:(备份小程序):

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import zipfile
import os
import sys
import time

__author__ = "YanZanG"

class Back_file(object):
    """程序备份类"""
    def __init__(self,file_name, time):
        self.file_name = file_name
        self.time = time

    def zip_file(self):
        print(os.getcwd())
        My_zip = zipfile.ZipFile(f"{self.time}_back.zip", "w")
        os.chdir(self.file_name)
        Count = True
        while (Count):
            for root, dirs, files in os.walk(self.file_name):
                for name in files:
                    file_result = os.path.join(root, name)
                    print(file_result)
                    My_zip.write(file_result, compress_type=zipfile.ZIP_DEFLATED)
                    Count = False
            My_zip.close()
            print(f"恭喜您,备份成功,备份文件为:{self.time}_back.zip")

def main():
    Count = True

    while (Count):
        print(f"Welcome to {__author__} backup system.")

        Your_file_input = input("请您输入您需要备份的目录:".strip())

        if os.path.exists(Your_file_input):
            os.chdir(Your_file_input)
            print("目录检测成功,正在备份文件,请稍后.....")
            Time = time.strftime("%Y_%m_%d%H%M%S", time.localtime())

            back_file = Back_file(Your_file_input, Time)
            back_file.zip_file()
        else:
            print("备份目录失败,您输入的内容检测失败,请您检查后再次输入,")


if __name__ == '__main__':

    while True:
        menu = {
            "1": "进入备份程序",
            "q": "退出此程序",
        }

        for k, v in menu.items():
            print(f"{k}、{v}")
        Your_input = input("请您选择:".strip()).upper()
        if Your_input == "1":
            main()


        elif Your_input == "Q":
            print("欢迎您再次使用,再见~")
            sys.exit()
        else:
            print("请您选择(1/q)")

实例2:(日志分析器):

#!/usr/bin/env python
# -*- coding:utf-8 -*-

import os
import re
import pickle
import sys
from color_me  import  ColorMe


__author__ = "YanZanG"

File_Path = r"F:\python_test1\Yankerp_test\result_test"
Log_Path = os.path.join(File_Path,"access.log")

IP_find = re.compile(r"((1\d{2}|25[0-5]|2[0-4]\d|[1-9]?\d)\.){3}(25[0-5]|2[0-4]\d|1\d{2}|[1-9]?\d)")
Url_find = re.compile(r"[a-zA-z]+://[^\s]*")


class Access(object):
    """
    程序功能类
    1:提供分析IP地址
    2:提供分析用户请求Url
    3:提供访问web页面的状态码
    4:将数据写入self.dict 同时pickle保存至目录中.
    """
    def __init__(self, log_path, File_Path):
        self.IP_database = {}
        self.Url_database = {}
        self.Web_status = {}
        self.log_path = log_path
        self.File_Path = File_Path

    def ip_address(self):
        """分析日志IP地址数量"""
        with open(self.File_Path) as f:
            Log_data = f.readlines()
            try:
                for log_ips in Log_data:
                    ip_search = IP_find.search(log_ips)
                    ip_result = ip_search.group()

                    if ip_result:
                        self.IP_database[ip_result] = self.IP_database.get(ip_result, 0) + 1
                        self.save_ip()
                    else:
                        print("error!!!")

            except Exception as e:
                print(e)

    def request_url(self):
        """分析日志请求url地址数量"""
        with open(self.File_Path) as f:
            data_result = f.readlines()

            try:
                for line in data_result:
                    web_url = Url_find.search(line)
                    if web_url:
                        self.Url_database[web_url.group()] = self.Url_database.get(web_url.group(), 0) + 1
                        self.save_url()

            except Entrance as e:
                print(e)

    def web_status(self):
        """分析日志请求状态码信息数量"""
        with open(self.File_Path) as f:
            web_status = f.readlines()

            try:
                for line in web_status:
                    web = line.split()[8]
                    if web:
                        self.Web_status[web] = self.Web_status.get(web, 0) + 1

            except Exception as e:
                print(e)

        for k, v in self.Web_status.items():
            print(f"状态码:{k} 访问次数:{v}次")

    def save_url(self):
        """保存日志url信息"""
        with open(f"{self.log_path}/web_url_log.pkl", "wb") as f:
            pickle.dump(self.Url_database, f)

    def save_ip(self):
        """保存日志IP地址访问信息"""
        with open(f"{self.log_path}/Access_log.pkl", "wb") as f:
            pickle.dump(self.IP_database, f)

    def read_url(self):
        """读取日志url信息"""
        with open(f"{self.log_path}/web_url_log.pkl", "rb") as f:
            url_data = pickle.load(f)
            self.Url_database.update(url_data)

            for k, v in self.Url_database.items():
                print(f"用户访问的网址为:{k} , 共访问次数为:{v}次")

            read_url_prompt = ColorMe(f"分析日志Url数据已保存在:{Log_Path}\web_url_log.pkl 文件中").green()
            print(read_url_prompt)

    def read_data(self):
        """读取日志IP地址信息"""
        with open(f"{self.log_path}/Access_log.pkl", "rb") as f:
            web_data = pickle.load(f)
            self.IP_database.update(web_data)

            for k, v in self.IP_database.items():
                print(f"用户IP地址为:'{k}' , 访问网站次数为:{v}次")

            read_data_prompt = ColorMe(f"分析日志IP地址数据已保存在:{Log_Path}\Access_log.pkl 文件中").green()
            print(read_data_prompt)


class Entrance(object):
    """
    程序入口
    1:使用反射调用类方法
    2:提供用户输入信息,调用Access类中的方法
    """
    def __init__(self, log_path, File_Path):
        self.log_path = log_path
        self.File_Path = File_Path

    def IP(self):
        """获取用户输入的目录及文件名称赋值-->Access类的属性,调用ip_address方法"""
        IP = Access(self.log_path, self.File_Path)

        IP.ip_address()
        IP.read_data()

    def web_url(self):
        """获取用户输入的目录及文件名称赋值-->Access类的属性,调用request_url方法"""
        URL = Access(self.log_path,self.File_Path)

        URL.request_url()
        URL.read_url()

    def web_status(self):
        """获取用户输入的目录及文件名称赋值-->Access类的属性,调用web_status方法"""
        Status = Access(self.log_path, self.File_Path)
        Status.web_status()

    def exit(self):
        """入口程序退出方法"""
        exit_result = ColorMe("退出成功,欢迎您再次使用~").green()
        print(exit_result)

        sys.exit()

    def menu(self):
        """Welcome欢迎信息- 输入菜单提供用户选择"""
        print(f"Welcome to {__author__} log analysis".center(60,"-"))

        menu = {
            "1" : "分析日志IP地址",
            "2" : "分析日志访问URL",
            "3" : "分析日志状态码",
            "Q" : "退出此程序"
        }

        menu2 = {
            "1" : "IP",
            "2" : "web_url",
            "3" : "web_status",
            "Q" : "exit"
        }

        Count = True
        while(Count):
            for k, v in menu.items():
                print(f"{k}、{v}")

            Your_input = input("请您输入您需要分析的日志内容:".strip()).upper()

            if hasattr(self, menu2.get(Your_input)):
                func = getattr(self, menu2.get(Your_input))
                func()


def menu():
    i = 0
    e = 3
    while (i < e):
        OS = ColorMe("系统提示:路径例:‘F:\python_test1\eeeee\’, 文件名称例:'access.log'").green()
        print(OS)

        File_Path = input("请您输入日志所存放的目录路径:".strip())
        Log_Path = input("请您输入日志名称:".strip())
        Log_data = os.path.join(File_Path, Log_Path)

        if os.path.exists(Log_data):

            de_Sssful = ColorMe("检测目录文件成功!!!").green()
            print(de_Sssful)
            A = Entrance(File_Path, Log_data)
            A.menu()
        else:
            i += 1
            menu_result = ColorMe(f"请您输入正确的目录,以及文件名称,您还有{e - i}次输入机会").red()
            print(menu_result)

if __name__ == '__main__':
    menu()

#TODO: 51memo

猜你喜欢

转载自blog.csdn.net/qq_39591494/article/details/83089633