python3读取csv文件任意行列

#读取每一行

#   reader = csv.reader(f) 此时reader返回的值是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格式文件写入数据
1.write()函数写入文本文件的也是字符串类型。
2.在’w’和’a’模式下,如果你打开的文件不存在,那么open()函数会自动帮你创建一个
3.'w’写入模式会给你暴力清空掉文件,然后再给你写入。如果你只想增加东西,而不想完全覆盖掉原文件的话,就要使用’a’模式,表示append,你学过,它是追加的意思。

file1 = open(D:\\new\\abc.txt',a')
file1.write(张无忌\n宋青书\n)
file1.close()

 

enumerate()

enumerate() 函数用于将一个可遍历的数据对象(如列表、元组或字符串)组合为一个索引序列,同时列出数据和数据下标 ,一般用在 for 循环当

以下是 enumerate() 方法的语法:     enumerate(sequence, [start=0])

  • sequence -- 一个序列、迭代器或其他支持迭代对象。
  • start -- 下标起始位置。

  返回 enumerate(枚举) 对象

seasons = [SpringSummerFallWinter]
print(list(enumerate(seasons)))               [(0,'Spring'),(1,'Summer'),(2,'Fall'),(3,'Winter')]
print(list(enumerate(seasons,start=1))  )    [(1,(4,'Winter')]
  普通for循环:
i = 0
seq = [onetwothreefor element in seq:
    print( i,seq[i])
    i +=1
'''
0 one
1 two
2 three
'''

for 循环使用 enumerate seq1 = [for j,element enumerate(seq1): (j,element) '''

#获取文件的编码方式
 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)[]

file_path = r
get_file_code(file_path)

 #判断文件的编码方式

f = open("",1)">")二进制格式读文件
i = 0
while True:
    (i)
    line = f.readline()
    if not line:
        break
    else:
        try:
             print(line)
#             print(line.decode('utf8'))
            line.decode(utf8)
            为了暴露出错误,最好此处不print
        except:
            (str(line))
    i += 1
#读取首行
filename=
with open(filename,1)">r')as f:  自行先判断文件的编码方式
    read=f.readlines()
    for index,info  enumerate(read):
        if index ==0:   这里判断
            这里输出的是字符串类型
            print(info)

#读取首行之外的所有行
filename=)as f:
    read=if index !=0:   print(info)
#读取前10行
filename=if index <10:  这里为索引,是 int 整形
            print(index,info)

 

#读取任意行,可根据index索引

 csv
filename=print(index)  自己根据index的数字判断

#读取第一和第二列

 

csv.reader(f)
     enumerate(read):
            这里输出的是列表类型
            print(info[:2])   [:2]代表的是读取第0列和第1列 ,第2列不包括

 

#读取除首行之外的第一,第二列

 

if index!=0:   这里加判断
            print(info[:2])

#读取最后两列

print(info[-2:])

#读第一行的第三列

filename=if index==0:
            print(info[2:3])

相关文章

使用OpenCV实现视频去抖 整体步骤: 设置输入输出视频 寻找帧...
前言 对中文标题使用余弦相似度算法和编辑距离相似度分析进行...
前言 之前尝试写过一个爬虫,那时对网页请求还不够熟练,用的...
前言 本文使用Python实现了PCA算法,并使用ORL人脸数据集进行...
前言 使用opencv对图像进行操作,要求:(1)定位银行票据的...
天气预报API 功能 从中国天气网抓取数据返回1-7天的天气数据...