zoukankan      html  css  js  c++  java
  • Python之读写文本数据

    知识点不多

    一:普通操作 

    # rt 模式的 open() 函数读取文本文件
    # wt 模式的 open() 函数清除覆盖掉原文件,write新文件
    # at 模式的 open() 函数添加write新文件
    with open("../../testData","rt",encoding="utf-8") as f :
        for line in f :
            print(line)
    
    
    # 写操作默认使用系统编码,可以通过调用 sys.getdefaultencoding() 来得到,也以通过传递一个可选的 encoding 参数给open()函数,几个常见的编码是ascii, latin-1, utf-8和utf-16
    # 关于换行符的识别问题:在Unix和Windows中是不一样的(分别是 
     和 
     )。 默认情况下,Python会以统一模式处理换行,识别普通换行符并将其转换为单个 
     字符
    # 如果你不希望这种默认的处理方式,可以给 open() 函数传入参数 newline=''
    f =open('somefile.txt', 'rt', newline='')
    
    
    # 最后一个问题就是文本文件中可能出现的编码错误
    # 如果修改了编码方式之后,编码错误还是存在的话,你可以给 open() 函数传递一个可选的 errors 参数来处理这些错误。
    m = open('sample.txt', 'rt', encoding='ascii', errors='replace')
    
    # 如果你经常使用 errors 参数来处理编码错误,也是不好的。
    # 原则是确保你总是使用的是正确编码。当模棱两可的时候,就使用默认的设置(通常都是UTF-8)。
    二:打印输出至文件中
    with open('../../testData', 'at') as f:
        print('Hello python!', file=f)
    
    # 使用其他分隔符或行终止符打印
    # 使用 print() 函数输出数据,但是想改变默认的分隔符或者行尾符,使用sep  end
    print("hello","cool","zzy",sep="***",end="!")   # hello***cool***zzy!
    
    #使用  str.join()
    print("***".join(("hello","cool","zzy")))  # hello***cool***zzy
    
    # 对比
    row = ("hello","cool","zzy")
    print(*row,sep="***")   # hello***cool***zzy
    三:读写字节数据
    # 读写二进制文件,比如图片,声音文件,使用模式为 rb 或 wb 的 open() 函数
    
    # 在读取二进制数据的时候,字节字符串和文本字符串的语义差异可能会导致一个潜在的陷阱:索引和迭代动作返回的是字节的值而不是字节字符串
    a='Hello World'
    print(a[0])   # H
    
    b = b'Hello World'  # Byte string
    print(b[0])  # 72  索引和迭代动作返回的是字节的值而不是字节字符串
    
    
    # 如果你想从二进制模式的文件中读取或写入文本数据,必须确保要进行解码和编码操作
    # 解码
    with open("../../testDta","rb") as f :
        data=f.read(16)
        text=data.decode("utf-8")
    
    # 编码
    with open("../../testDta","wb") as d :
        text="hello"
        f.write(text.encode("utf-8"))
    四:文件不存在才能写入
    一个替代方案是先测试这个文件是否存在,像下面这样:
    import os
    if not os.path.exists("../../testData"):
        with open("../../testData", "wt") as f:
            f.write("")
    else:
        print('File already exists!')
    最优解决
    # 文件中写入数据,不允许覆盖已存在的数据,可以用"xt",这个参数会判断文件是否已经存在(不管是否有内容,也不管内容是怎样的),如果有会报错FileExistsError:
    with open("../../testData","wt") as f :
        f.write("")
    with open("../../testData","xt") as f :
        f.write("你好")    # FileExistsError: [Errno 17] File exists: '../../testData'
    五:读压缩文件
    import gzip
    with gzip.open('somefile.gz', 'rt') as f:
        text = f.read()
    
    # bz2 compression
    import bz2
    with bz2.open('somefile.bz2', 'rt') as f:
        text = f.read()
    
    # 写入压缩数据
    import gzip
    with gzip.open('somefile.gz', 'wt') as f:
        f.write(text)
    
    # bz2 compression
    import bz2
    with bz2.open('somefile.bz2', 'wt') as f:
        f.write(text)
    读写压缩数据  如果你不指定模式,那么默认的就是二进制模式,如果这时候程序想要接受的是文本数据,那么就会出错。
    gzip.open() 和 bz2.open() 接受跟内置的 open() 函数一样的参数, 包括 encoding,errors,newline 等等。
    可以使用 compresslevel 这个可选的关键字参数来指定一个压缩级别,默认的等级是9,也是最高的压缩等级。等级越低性能越好,但是数据压缩程度也越低。
    with gzip.open('somefile.gz', 'wt', compresslevel=5) as f:
        f.write(text)
    六:固定大小记录的文件迭代
    from functools import partial
    RECORD_SIZE= 32
    # somefile.data是二进制文件
    with open('somefile.data', 'rb') as f:
        records = iter(partial(f.read, RECORD_SIZE), b'')
        for r in records:
            ...
     

     
  • 相关阅读:
    程序员的人品
    【转】telnet使用 删除foxmail不能收取的邮件
    35岁以后我在干什么?
    面试
    程序员基本知识数制
    一事无成
    经过XssFilter替换特殊字符后再经zuul路由转发httpEntity缺少内容
    android跳转到市场进行评价 market://search?q
    使用IntelliJ 12.1.12开发android程序
    重定向
  • 原文地址:https://www.cnblogs.com/zzy-9318/p/10497428.html
Copyright © 2011-2022 走看看