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
three
# for 循环使用 enumerate
seq1 = ['one', 'two', 'three']
for j, element in enumerate(seq1):
print (j, element)
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:
# print(line)
# print(line.decode('utf8'))
line.decode('utf8')
#为了暴露出错误,最好此处不print
except:
print(str(line))
i += 1
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的数字判断
读取第一和第二列
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])
读取最后两列
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])