-
CSV文件写入
'''写:向csv中写入内容 1.导入 csv 模块 2.使用open打开要操作的文件,以写入模式打开 mode='w' 3.通过csv.writer(stream) ---> writer对象 4.使用writer对象向文件中写入内容:writerow(['','','']),writerows([[],[],[]]) 5.关闭''' import csv # newline="" 去除csv的空行 with open('../files/cards1.csv', 'w',newline="") as csv_stream: # 转成writer writer = csv.writer(csv_stream) # 使用writer写入列名 writer.writerow(['name', 'telephone', 'qq']) # 写入具体的内容 writer.writerows([('aa', '123456', '123456'), ('aa', '123456', '123456'), ('aa', '123456', '123456')]) print('写入完毕!')
-
CSV文件读取
'''读取: 从csv中读取内容 1.导入 csv 模块 2.使用open打开要操作的文件,以读取模式打开 mode='r' 3.通过csv.reader(stream) ---> reader对象 4.直接使用for...in 遍历reader对象,每循环一次就是获取csv中一行的内容 5.关闭 ''' import csv with open('../files/cards.csv') as read_stream: reader = csv.reader(read_stream) for line in reader: print(line) # line就是一个列表
-
内存操作
''' 使用临时的内存操作数据: 1. stringIO 字符串 2. bytesIO 字节 Input ----》 read Output ----》 writer ''' # string # import csv import io # python给我开辟一块内存专门存放字符串,还可以从这块内存中读和写 sio = io.StringIO() sio.write('hello world哈哈哈哈') sio.write('hello kitty') sio.flush() # 读取内容,但是内存中使用read() readline() readlines() 都无法获取内容 content = sio.read() print(content) # 使用getvalue()获取内容 content = sio.getvalue() print(content) sio.close() #bytes import io bio = io.BytesIO() bio.write('哈哈哈哈'.encode('utf-8')) # 编码 bio.write('呵呵呵呵'.encode('utf-8')) bio.write('嘿嘿嘿嘿'.encode('utf-8')) content = bio.getvalue() print(content.decode('utf-8')) # 解码 bio.close()
文件操作——csv文件+内存操作
最新推荐文章于 2023-11-09 20:23:05 发布