GVKun编程网logo

Python获取同目录下json文件内容(python读取同一个目录一个文件)

23

这篇文章主要围绕Python获取同目录下json文件内容和python读取同一个目录一个文件展开,旨在为您提供一份详细的参考资料。我们将全面介绍Python获取同目录下json文件内容的优缺点,解答p

这篇文章主要围绕Python获取同目录下json文件内容python读取同一个目录一个文件展开,旨在为您提供一份详细的参考资料。我们将全面介绍Python获取同目录下json文件内容的优缺点,解答python读取同一个目录一个文件的相关问题,同时也会为您带来Python uiautomation获取微信电脑版控件内容!聊天列表、聊天记录全都可获取、Python 修改文件内容3种方法(替换文件内容)、python 删除一个目录下某个类型的文件,以及删除目录下子目录的所有文件、python 获取当前目录下的文件目录和文件名的实用方法。

本文目录一览:

Python获取同目录下json文件内容(python读取同一个目录一个文件)

Python获取同目录下json文件内容(python读取同一个目录一个文件)

这种写法可以替代配置文件的传参,效率更高 

json文件:baittype.json

{
    "bait_type":[
        {
            "type":"ssh","user":"root","password":"qazwsx","start_time":"14:00:00","end_time":"15:00:00"
        },{
            "type":"telnet","user":"yvan","password":"password","start_time":"15:00:00","end_time":"16:00:00"
        },{
            "type":"ftp","user":"myuser","password":"mypasswd","start_time":"16:00:00","end_time":"17:00:00"
        }
    ]
}

源码:

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


import os
import json


bait_type_path = os.path.dirname(__file__)

with open(os.path.join(bait_type_path,'baittype.json')) as fp:
    data = json.load(fp)

bait_data = []

for entry in data["bait_type"]:
    bait = {}
    bait["type"] = entry["type"]
    bait["start_time"] = entry["start_time"]
    bait["end_time"] = entry["end_time"]
    bait_data.append(bait)

 

Python uiautomation获取微信电脑版控件内容!聊天列表、聊天记录全都可获取

Python uiautomation获取微信电脑版控件内容!聊天列表、聊天记录全都可获取

Python uiautomation

Python uiautomation 是一个用于自动化 GUI 测试和操作的库,它可以模拟用户操作来执行各种任务。通过这个库,可以使用Python脚本模拟人工点击,人工操作界面。本文使用 Python uiautomation 进行微信电脑版的操作。

微信电脑版

以下是本次实验的版本号。

image.png

你需要安装 uiautomation

pip install uiautomation

然后使用 uiautomation 进行操作。

代码

import time
import uiautomation as auto
import re
from plyer import notification

notification_history = {}  # 历史消息

def check_wechat_messages():

    # 获取微信窗口
    wechat_win = auto.WindowControl(Name="微信", ClassName="WeChatMainWndForPC")

    shoukuanWin = wechat_win.ListControl(Name="会话")
    bbb = shoukuanWin.GetChildren()

    for chatMsg in bbb:
        if "条新消息" in chatMsg.Name:

            # 计算消息条数
            match = re.match(r''([a-zA-Z0-9]+)(\d+)条新消息'', chatMsg.Name)

            if match:
                nickname = match.group(1)
                message_count = int(match.group(2))

                printInfo = f"{nickname} 给你发送了 {message_count} 条消息"
                print(printInfo)
                print("------------")

                # 获取消息列表控件
                xiaoxis = wechat_win.ListControl(Name="消息")
                
                # 获取消息列表控件的子控件
                xiaoxi_children = xiaoxis.GetChildren()

                # 获取最后一个子控件
                last_xiaoxi = xiaoxi_children[-1]

                # 打印最后一条消息的内容
                print(last_xiaoxi.Name)

                # 在指定时间内不重发
                last_notification_time = notification_history.get((nickname, message_count), 0)
                current_time = time.time()

                if current_time - last_notification_time > 15:

                    # 依次发送
                    notification_title = f"来自 {nickname} 的 {message_count} 条消息"
                    notification_message = f"{last_xiaoxi.Name}"

                    notification.notify(
                        title=notification_title,
                        message=notification_message,
                        app_name="WeChat"
                    )

                    # 更新日志
                    notification_history[(nickname, message_count)] = current_time

if __name__ == "__main__":
    try:
        while True:
            check_wechat_messages()
            time.sleep(2)  #2秒检测一次UI组件
    except KeyboardInterrupt:
        print("程序退出~")
    except Exception as e:
        print(f"程序执行出现了问题: {str(e)}")

代码解析:

以上代码使用 uiautomation 实时获取微信聊天列表的消息状态,一旦有消息发过来,就会获取到发送人的微信昵称以及发送的消息内容、消息个数。

每2秒获取一次UI控件的内容,实测挂在后台对CPU和内存占用并无明显影响。

结合Python uiautomation的各种用法,可以做成自动回复的功能。

UISpy.exe

使用这款软件,可以获取到微信电脑版大部分控件的内容。

例如:微信聊天列表、群名称、好友微信昵称、群人数、微信号等。

image.png

还可以获取到群内的每一条聊天内容,获取到你跟好友的聊天记录。

image.png

只要 UISpy.exe 可获取到的控件内容,那么你用 Python就可以获取到。

作者

TANKING

Python 修改文件内容3种方法(替换文件内容)

Python 修改文件内容3种方法(替换文件内容)

一、修改原文件方式

def alter(file,old_str,new_str):
    """
    替换文件中的字符串
    :param file:文件名
    :param old_str:就字符串
    :param new_str:新字符串
    :return:
    """
    file_data = ""
    with open(file,"r",encoding="utf-8") as f:
        for line in f:
            if old_str in line:
                line = line.replace(old_str,new_str)
            file_data += line
    with open(file,"w",encoding="utf-8") as f:
        f.write(file_data)

alter("file1","09876","python")@H_301_5@ 

二、把原文件内容和要修改的内容写到新文件中进行存储的方式

2.1 python字符串替换的方法,修改文件内容

import os
def alter(file,new_str):
    """
    将替换的字符串写到一个新的文件中,然后将原文件删除,新文件改为原来文件的名字
    :param file: 文件路径
    :param old_str: 需要替换的字符串
    :param new_str: 替换的字符串
    :return: None
    """
    with open(file,encoding="utf-8") as f1,open("%s.bak" % file,encoding="utf-8") as f2:
        for line in f1:
            if old_str in line:
                line = line.replace(old_str,new_str)
            f2.write(line)
    os.remove(file)
    os.rename("%s.bak" % file,file)

alter("file1","python","测试")@H_301_5@ 

2.2 python 使用正则表达式 替换文件内容 re.sub 方法替换

import re,os
def alter(file,new_str):

    with open(file,encoding="utf-8") as f2:
        for line in f1:
            f2.write(re.sub(old_str,new_str,line))
    os.remove(file)
    os.rename("%s.bak" % file,file)
alter("file1","admin","password")@H_301_5@

python 删除一个目录下某个类型的文件,以及删除目录下子目录的所有文件

python 删除一个目录下某个类型的文件,以及删除目录下子目录的所有文件

import os
for files in os.listdir(''output''):
        if files.endswith(".py"):
            os.remove(os.path.join(''output'',files))

下面是删除所有以及子目录

import os,shutil

def del_file(filepath):
    """
    删除某一目录下的所有文件或文件夹
    :param filepath: 路径
    :return:
    """
    del_list = os.listdir(filepath)
    for f in del_list:
        file_path = os.path.join(filepath, f)
        if os.path.isfile(file_path):
            os.remove(file_path)
        elif os.path.isdir(file_path):
            shutil.rmtree(file_path)
del_file(''test_fold'')

 

python 获取当前目录下的文件目录和文件名

python 获取当前目录下的文件目录和文件名

os模块下有两个函数:

  os.walk()

  os.listdir()

 

1 # -*- coding: utf-8 -*-   
2       
3     import os  
4       
5     def file_name(file_dir):   
6         for root, dirs, files in os.walk(file_dir):  
7             print(root) #当前目录路径  
8             print(dirs) #当前路径下所有子目录  
9             print(files) #当前路径下所有非目录子文件

输出格式为:

  当前文件目录路径

  当前路径下子文件目录(若存在, 不存在则为 [] )

  当前路径下非目录子文件(仅为子文件的文件名)

    

    子文件1路径

    子文件1下的子文件目录

    子文件1下的非目录子文件

 

    子文件2路径

    子文件2下的子文件目录

    子文件2下的非目录子文件

 

 1 # -*- coding: utf-8 -*-   
 2       
 3     import os  
 4       
 5     def file_name(file_dir):   
 6         L=[]   
 7         for root, dirs, files in os.walk(file_dir):  
 8             for file in files:  
 9                 if os.path.splitext(file)[1] == ''.jpeg'':  
10                     L.append(os.path.join(root, file))  
11         return L  
12 
13 
14 #其中os.path.splitext()函数将路径拆分为文件名+扩展名

 

 1 # -*- coding: utf-8 -*-  
 2     import os  
 3       
 4     def listdir(path, list_name):  #传入存储的list
 5         for file in os.listdir(path):  
 6             file_path = os.path.join(path, file)  
 7             if os.path.isdir(file_path):  
 8                 listdir(file_path, list_name)  
 9             else:  
10                 list_name.append(file_path)

递归输出当前路径下所有非目录子文件

    

  

 

今天关于Python获取同目录下json文件内容python读取同一个目录一个文件的介绍到此结束,谢谢您的阅读,有关Python uiautomation获取微信电脑版控件内容!聊天列表、聊天记录全都可获取、Python 修改文件内容3种方法(替换文件内容)、python 删除一个目录下某个类型的文件,以及删除目录下子目录的所有文件、python 获取当前目录下的文件目录和文件名等更多相关知识的信息可以在本站进行查询。

本文标签: