文件操作——csv文件+内存操作

  1. 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('写入完毕!')
    

     

  2. 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就是一个列表
    

     

  3. 内存操作

    '''
      使用临时的内存操作数据:
      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()
    

     

评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值