首页 > 编程语言 > 详细

python习题_读写csv格式的文件

时间:2019-07-07 22:35:10      阅读:160      评论:0      收藏:0      [点我收藏+]

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) + "\n"
    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\n"
    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

 

python习题_读写csv格式的文件

原文:https://www.cnblogs.com/jszfy/p/11147598.html

(0)
(0)
   
举报
评论 一句话评论(0
关于我们 - 联系我们 - 留言反馈 - 联系我们:wmxa8@hotmail.com
© 2014 bubuko.com 版权所有
打开技术之扣,分享程序人生!