Python3读取CSV文件任意行列与写入操作详解
本文详细介绍Python3中CSV文件的读取与写入方法。通过csv模块和enumerate函数,实现读取任意行、指定列、首行及最后几列等灵活操作。同时涵盖文件写入模式(w/a)的区别、自动创建文件机制,以及利用chardet库检测文件编码的技巧,帮助开发者高效处理CSV数据。
本文提供Python3环境下读取CSV文件任意行列的代码示例,内容详实,对学习和工作具有参考价值。
逐行读取与写入CSV文件
逐行读取CSV文件内容
使用csv.reader(f)创建读取器对象,该对象返回CSV文件中每一行的数据列表。
#读取每一行
filename='D:\\file_information1.csv'
import csv
with open(filename,newline = '',encoding = 'utf-8') as f: #参数encoding = 'utf-8'防止出现乱码
reader = csv.reader(f) #使用csv的reader()方法,创建一个reader对象 csv.reader()读取结果是列表
for row in reader: #遍历reader对象的每一行
print(row)
向CSV格式文件写入数据的方法
write()函数用于将字符串类型的数据写入文本文件。
在'w'(写入)和'a'(追加)模式下,若目标文件不存在,open()函数会自动创建该文件。
'w'模式会清空文件内容后重新写入;若需保留原文件内容并追加数据,应使用'a'模式(append)。
file1 = open('D:\\new\\abc.txt','a',encoding='utf-8')
file1.write('张无忌\n')
file1.write('宋青书\n')
file1.close()
enumerate函数详解
enumerate()函数用法
enumerate()函数将可遍历对象(如列表、元组或字符串)组合为索引序列,同时返回数据和下标,常用于for循环中。
enumerate()方法的语法格式为:enumerate(sequence, [start=0])。
- sequence参数表示一个序列、迭代器或其他支持迭代对象。
- start参数指定下标的起始位置,默认为0。
该函数返回一个enumerate(枚举)对象。
seasons = ['Spring', 'Summer', 'Fall', 'Winter']
print(list(enumerate(seasons))) # [(0, 'Spring'), (1, 'Summer'), (2, 'Fall'), (3, 'Winter')]
print(list(enumerate(seasons, start=1)) ) # [(1, 'Spring'), (2, 'Summer'), (3, 'Fall'), (4, 'Winter')]
# 普通for循环:
i = 0
seq = ['one', 'two', 'three']
for element in seq:
print( i, seq[i])
i +=1
'''
one
two
three
'''
# for 循环使用 enumerate
seq1 = ['one', 'two', 'three']
for j, element in enumerate(seq1):
print (j, element)
'''
one
two
three
'''
文件编码检测与行列读取技巧
获取文件的编码方式
import chardet
def get_file_code(file_path):
with open(file_path, 'rb') as f:
data = f.read()
print('获取到的CSV文件编码为:%s' % (chardet.detect(data)['encoding']))
return chardet.detect(data)['encoding']
file_path = r'D:\\file_information1.csv'
get_file_code(file_path)
判断文件编码的具体实现
f = open("D:\\file_information1.csv","rb")#二进制格式读文件
i = 0
while True:
print(i)
line = f.readline()
if not line:
break
else:
try:
# print(line)
# print(line.decode('utf8'))
line.decode('utf8')
#为了暴露出错误,最好此处不print
except:
print(str(line))
i += 1
读取CSV文件的首行数据
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f: #自行先判断文件的编码方式
read=f.readlines()
for index,info in enumerate(read):
if index ==0: #这里判断
#这里输出的是字符串类型
print(info)
读取除首行之外的所有行
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=f.readlines()
for index,info in enumerate(read):
if index !=0: #这里判断
print(info)
读取文件的前10行
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=f.readlines()
for index,info in enumerate(read):
if index <10: #这里为索引,是 int 整形
print(index,info)
根据index索引读取任意指定行
import csv
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=f.readlines()
for index,info in enumerate(read):
print(index) #自己根据index的数字判断
读取CSV文件的第一列和第二列
import csv
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=csv.reader(f)
for index,info in enumerate(read):
#这里输出的是列表类型
print(info[:2]) #[:2]代表的是读取第0列和第1列 ,第2列不包括
读取除首行之外的第一列和第二列
import csv
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=csv.reader(f)
for index,info in enumerate(read):
if index!=0: #这里加判断
print(info[:2])
读取CSV文件的最后两列
import csv
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=csv.reader(f)
for index,info in enumerate(read):
print(info[-2:])
读取第一行中的第三列数据
filename='D:\\file_information1.csv'
with open(filename,'r',encoding='utf-8')as f:
read=csv.reader(f)
for index,info in enumerate(read):
if index==0:
print(info[2:3])
以上内容为本文总结,希望能为读者提供帮助,欢迎继续支持本站。
免责声明:本文内容仅供参考,不代表本站观点。转载或引用请注明出处。









