with open("cars.txt", "r") as file:
for line in file:
print(f"我的汽车是:{line.rstrip()}")
with open(...)语句确保文件在使用完毕后自动关闭,即使发生异常。rstrip()方法去除行尾的换行符。
排序和处理数据:
以下代码读取文件,将数据排序后打印:
cars = []
with open("cars.txt", "r") as file:
for line in file:
cars.append(line.rstrip())
for car in sorted(cars):
print(f"我的汽车是:{car}")
CSV文件操作:
逗号分隔值(CSV)文件常用于存储表格数据。 以下代码演示如何读取和写入CSV文件:
读取CSV:
import csv
students = []
with open("students.csv", "r") as file:
reader = csv.DictReader(file)
for row in reader:
students.append(row)
for student in sorted(students, key=lambda student: student["name"]):
print(f"{student['name']} 在 {student['house']}")
写入CSV:
import csv
name = input("请输入您的姓名:")
house = input("请输入您的学院:")
with open("students.csv", "a", newline='') as file:
fieldnames = ["name", "house"]
writer = csv.DictWriter(file, fieldnames=fieldnames)
writer.writerow({"name": name, "house": house})
报错“not a supported wheel on this platform”主因是.whl文件与当前Python环境(版本、ABI、平台)不匹配;需用pip debug查看标签,严格核对文件名三段标识,并优先从PyPI下载对应版本。 pip install 本地 .whl 文件报错“not a supported wheel on this platform” 这是最常见的卡点:你下载的 ...