zoukankan      html  css  js  c++  java
  • 文件处理02

    1.光标移动

      read(3)

      1).文件打开方式为文本模式时,代表读取3个字符

      2).文件打开为b模式时,代表读取3个字节,中文一个字符代表3个字节,英文一个字符就是一个字节。其余的文件内光标移动就是以字节为单位的。seek有三种移动方式0,1,2,其中1,2必须是在b模式下运行,无论哪种模式,都是以字节为单位移动的。truncate是截断,文件的打开方式是可写,不能用w或者w+来写,这样的话原来的文件就会被清空,所以我们可以用r+或者a+来进行打开

    2.文件的修改

      1)先将数据由硬盘读到内存(读文件) 

      2)在内存中完成修改(字符串的替换)

      3)再覆盖原来的内容(写文件)

    with open(r'test02.txt','r',enconding='utf-8') as f:
        data = f.read()
        print(data)
        print(type(data))
    with open(r'test02.txt','w',enconding='utf-8') as f:
        res = data.replace('egon','jason')
        print(data)
        f.write(res)
    

      方式2:

      1)创建一个新文件

      2)每行每行读取老文件内容到内存进行修改

      3)将老文件删除,新文件名字改成老文件名字

    import os
    
    
    with open (r'test02.txt','r',enconding='utf-8')  as read_f,
         open(r'test02.swap','a',encond='utf-8') as write_f:
         for line in read_f:
            new_line = line_replace('egon','jason')
            write_f.write(new_line)
    os.remove('testo2.txt')
    os.rename('test.swp','test02.txt')
    

      

    生前无需久睡,死后自会长眠,努力解决生活中遇到的各种问题,不畏将来,勇敢面对,加油,你是最胖的,哈哈哈
  • 相关阅读:
    CodeForces 650C Table Compression
    HDU 5632 Rikka with Array [想法题]
    HDU 4352 XHXJ's LIS
    HDU 5634 Rikka with Phi
    HDU 4763 Theme Section
    LightOJ 1342 Aladdin and the Magical Sticks [想法题]
    HDU 4578 Transformation
    POJ 1177 Picture
    HDU 4614 Vases and Flowers
    SPOJ AEROLITE
  • 原文地址:https://www.cnblogs.com/panshao51km-cn/p/11152553.html
Copyright © 2011-2022 走看看