读取文件的方法(小Demo)

import json


class ReadJson2Url(object):
    """读取文件并提取保存字段"""
    def __init__(self):
        try:
            self.path = input("请输入要读取的路径: ")
        except Exception as e:
            print("路径错误", e)
        else:
            print("读取成功")
            print("-" * 50)
        try:
            self.input_name = input("请输入要读取的字段名: ")
        except Exception as e:
            print("字段输入错误", e)
        else:
            print("正在读取字段中...")
            print("-" * 50)

        try:
            self.output_name = input("请输入要存储的字段名: ")
        except Exception as e:
            print("字段未知错误", e)
        else:
            print("正在存储字段中...")
            print("-" * 50)

        try:
            self.to_path = input("请输入存储的路径: ")
        except Exception as e:
            print("路径错误", e)
        else:
            print("正在存储...")


    def get_json(self):
        """读取文件中的url并生成json文件"""
        # 读取json文件并转为python格式
        with open(self.path, "r") as f:
            res = json.load(f)
        url_list = []
        for i in res:
            url_list.append(i[self.input_name])
        return url_list

    def get_url(self, url_list):
        """获取文件中的url,并转为字典"""
        urls = []
        for url in url_list:
            item = {}
            item[self.output_name] = url
            urls.append(item)
        return urls

    def url_2_json(self, urls):
        """将url存储为json文件"""
        try:
            with open(self.to_path, "w") as f:
                f.write(json.dumps(urls))
        except Exception as e:
            print("存储失败,原因为:", e)
        else:
            print("存储成功")


if __name__ == "__main__":
    while True:
        # 输入文件路径
        read_json = ReadJson2Url()

        # 读取文件
        url_list = read_json.get_json()

        # 获取url
        urls = read_json.get_url(url_list)

        # 转换为json文件
        read_json.url_2_json(urls)
    


猜你喜欢

转载自blog.csdn.net/Li_G_yuan/article/details/83305387