zoukankan      html  css  js  c++  java
  • python习题_读写csv格式的文件

    1.读写TXT文件

    # *_* coding : UTF-8 *_*
    # 开发人员 : zfy
    # 开发时间 :2019/7/7 16:26
    # 文件名 : lemon_10_file.PY
    # 开发工具 : PyCharm
    
    person_info = [{"name": "江辰", "age": 17, "gender": "", "hobby": "跑步", "motto": "ABC"},
                   {"name": "陈小希", "age": 16, "gender": "", "hobby": "画画", "motto": "小美好"},]
    
    
    def handle_date(one_list):
        content = ""
        for item in one_list:
            temp_list =[]
            for i in item.values():
                temp_list.append(str(i))
            content = content + ",".join(temp_list) + "
    "
        return content
    
    
    def main(file, content):
        with open(file, mode="a", encoding="utf-8") as one_file:
            one_file.write(content)
    
    
    if __name__ == "__main__":
        headline = "name,age,gender,hobby,motto
    "
        main("test.txt", headline)
        main("test.txt", handle_date(person_info))
    View Code

    2.读写csv文件

    def write_from_dict(file_path, field_name, datas):
        """
        将来自字典的数据写入csv文件中
        :param file_path: 文件的存放路径
        :param field_name: 列名所在的列表
        :param datas:嵌套字典的列表
        :return:
        """
        with open(file_path, mode="w", encoding="utf-8", newline="") as csv_file:
            writer = csv.DictWriter(csv_file, fieldnames = field_name)
            writer.writeheader()
            writer.writerows(datas)
    
            # for item in datas:
            #     writer.writerow(item)
    
    
    def read_from_csv(file_path):
        """
        将csv文件中的内容读出
        :param file_path: csv文件的路径
        :return:
        """
        with open(file_path, mode="r", encoding="utf-8") as csv_file:
            reader = csv.reader(csv_file)
            for row in reader:
                if row:
                    print("{},{},{},{}".format(*row))
    
    
    def csv_main():
        file_path = "test.txt"
        field_names = ['name', 'age', 'gender', 'hobby', 'motto']
        write_from_dict(file_path, field_names, person_info)
        read_from_csv(file_path)
    View Code
  • 相关阅读:
    【软件测试】软件缺陷粗浅认识及白盒测试举例
    【软件测试】等价类划分
    【软件测试】对本门课程粗浅理解
    阿里云服务器本地ping超时,远程可以正常ping通
    不忘初心
    开源框架、控件、组件、插件记录
    Flex中窗口可随意拖拽功能实现
    初探数据类型相关问题
    [TSCTF-J 2021] 解题报告
    指针
  • 原文地址:https://www.cnblogs.com/jszfy/p/11147598.html
Copyright © 2011-2022 走看看