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

 

posted on 2019-07-07 20:38  青柠锦鲤  阅读(309)  评论(0编辑  收藏  举报