python使用With Open函数操作CSV格式文件

一、使用With Open函数读写文件

1、为什么要使用With Open函数

在读写文件时很有可能发生错误,如果使用正常的open()函数读写就不能保证能正常的关闭文件,为了减少代码量和文件安全,推荐使用With Open函数进行读写。

2、介绍open()函数的四个参数

  • file : 读写文件的路径(最好写绝对路径),第一个位置参数
  • mode : 对文件的操作(如r, w, rb, a等,默认只读),第二个位置参数
  • encoding :以某编码读写文件(如gbk, utf-8,默认encoding=‘gbk’)
  • errors : 忽略编码不规范(errors=‘ignore’ )

3、文件读写测试

准备一个路径为:E:\Desktop\test.txt,编码为:utf-8 的 txt 文档

python csv open 方式 python中with open写csv文件_CSV

# file="E:\\Desktop\\test.txt",mode='r',encoding='utf-8'
with open("E:\\Desktop\\test.txt", 'r', encoding='utf-8') as file:
    print(file.read())

运行结果:

python csv open 方式 python中with open写csv文件_CSV_02


如果使用非utf-8编码读取,即默认编码

with open("E:\\Desktop\\test.txt", 'r') as file:
    print(file.read())

运行结果:UnicodeDecodeError

python csv open 方式 python中with open写csv文件_CSV_03


分析:这是文件编码和读取编码不一致导致的UnicodeDecodeError,而这时候errors参数的作用就能体现出来了,将参数errors=‘ignore’ 加如代码中来

with open("E:\\Desktop\\test.txt", errors='ignore') as file:
    print(file.read())

运行结果:

正常编码应该是:我是一个案例

python csv open 方式 python中with open写csv文件_python csv open 方式_04


分析:添加errors='ignore’之后,在读取文件时会忽略UnicodeDecodeError,对文件进行操作

如果需要打开二进制文件

要读取二进制文件,比如图片、视频等等,用’rb’模式打开文件

with open("E:\\Desktop\\test.png", 'rb') as file:
	# 结果为十六进制表示的字节
    print(file.read())

二、操作CSV格式文件

1、csv格式文件说明

CSV是一种以逗号分隔数值的文件类型,在数据库或电子表格中,常见的导入导出文件格式就是CSV格式,CSV格式存储数据通常以纯文本的方式存数数据表

准备一个test.csv文件

python csv open 方式 python中with open写csv文件_csv_05

2、对CSV文件操作

(1)按行读取文件

import csv

with open("E:\\Desktop\\test.csv", 'r', encoding='utf-8') as file:
    reader = csv.reader(file)
    rows = [row for row in reader]
    print(rows[0])    # 读取第一行数据

运行结果:

python csv open 方式 python中with open写csv文件_csv_06

注意 : 如果结果出现\ufeff这时候我们需要修改读取的编码为encoding=‘utf-8-sig’

python csv open 方式 python中with open写csv文件_Desktop_07

(2)按列读取文件

import csv

with open("E:\\Desktop\\test.csv", 'r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    column = [row[0] for row in reader]
    print(column)

运行结果:

python csv open 方式 python中with open写csv文件_CSV_08


(3)读全部文件

import csv

with open("E:\\Desktop\\test.csv", 'r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

运行结果:

python csv open 方式 python中with open写csv文件_Desktop_09


(4)写入数据

import csv

# 写入数据
with open("E:\\Desktop\\test.csv", 'a', encoding='utf-8') as file:
    row = ['小冷', '男', '19']
    csv.writer(file).writerow(row)

# 查看数据是否写入成功
with open("E:\\Desktop\\test.csv", 'r', encoding='utf-8-sig') as file:
    reader = csv.reader(file)
    for row in reader:
        print(row)

运行结果

python csv open 方式 python中with open写csv文件_CSV_10