[Python] Read and Parse Files in Python

本文介绍了如何使用Python进行文件的基本读写操作,并演示了如何利用csv模块读取CSV文件内容,以及如何通过json模块解析JSON数据。同时,还展示了如何向文本文件追加内容及如何创建JSON文件。

摘要生成于 C知道 ,由 DeepSeek-R1 满血版支持, 前往体验 >

This lesson will teach you how to read the contents of an external file from Python. You will also learn how to use the python csv module to read and parse csv data, as well as the json module to read and parse json data.

 

# f = open('animals.csv')

# for line in f:
#     print(line)

# f.close()

# with open('animals.csv', 'r') as f:
#     print(f.read())
    
# import csv
# with open('animals.csv', 'r') as f:
#     animals = csv.reader(f)
#     for row in animals:
#         if row[-1] == 'True':
#             print("{0} is a {1} and is housebroken".format(row[0], row[1]))
#         elif row[-1] == 'False':
#             print("{0} is a {1} and is not housebroken!".format(row[0], row[1]))

# import json
# with open('animals.json', 'r') as r:
#     data = json.load(r)
#     for row in data:
#         print(row['name'])

# f = open('cars.txt', 'a')
# cars = ['chevy', 'tesla', 'ford']
# for car in cars:
#     f.write(car + '\n')

# f.close()

# with open('cars.txt', 'a') as f:
#     cars = ['chevy', 'vw', 'mazda']
#     for car in cars:
#         f.write(car + '\n')

cars = [
    {"make": "chevy"},
    {"make": "tesla"},
    {"make": "porsche"}
]
import json
with open('cars.json', 'w') as f:
    json.dump(cars, f)

 

转载于:https://www.cnblogs.com/Answer1215/p/8033310.html

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值