1.读取csv文件
读取文本文件时,需要在使用open
函数时指定好带路径的文件名(可以使用相对路径或绝对路径)并将文件模式设置为'r'
(如果不指定,默认值也是'r'
),然后通过encoding
参数指定编码(如果不指定,默认值是None,那么在读取文件时使用的是操作系统默认的编码),如果不能保证保存文件时使用的编码方式与encoding参数指定的编码方式是一致的,那么就可能因无法解码字符而导致读取失败。下面的例子演示了如何读取一个纯文本文件。
"""
读取CSV文件
Version: 0.1
Author: Maxwell
Date: 2024-05-07
"""
import csv
filename = 'example.csv'
try:
with open(filename) as f:
reader = csv.reader(f)
data = list(reader)
except FileNotFoundError:
print('无法打开文件:', filename)
else:
for item in data:
print('%-30s%-20s%-10s' % (item[0], item[1], item[2]))
2.写入CSV文件
"""
写入CSV文件
Version: 0.1
Author: Maxwell
Date: 2024-05-07
"""
import csv
class Teacher(object):
def __init__(self, name, age, title):
self.__name = name
self.__age = age
self.__title = title
self.__index = -1
@property
def name(self):
return self.__name
@property
def age(self):
return self.__age
@property
def title(self):
return self.__title
filename = 'teacher.csv'
teachers = [Teacher('Max', 28, '老师'),Teacher('Maxwell', 26, '专家')]
try:
with open(filename, 'w') as f:
writer = csv.writer(f)
for teacher in teachers:
writer.writerow([teacher.name, teacher.age, teacher.title])
except BaseException as e:
print('无法写入文件:', filename)
else:
print('保存数据完成!')
3.异常机制——处理程序在运行时间可能发生的状态
"""
异常机制 - 处理程序在运行时可能发生的状态
Version: 0.1
Author: Maxwell
Date: 2024-05-07
"""
input_again = True
while input_again:
try: