跳转至

读写文件

读文件

  • 读文本

    f = open('file.txt')try:c = f.read( )finally:f.close( )

  • 读二进制文件

    f = open('data','rb') - 读固定字节 f = open('file', 'rb')try:while True:chunk = f.read(100)if not chunk:breakdo_something_with(chunk)finally:f.close( )

  • 读每行 l = f.readlines( )


写文件

  • 写文本文件

    output = open('data', 'w')
    
  • 写二进制文件

    output = open('data', 'wb')
    

  • 追加写文件

    output = open('data', 'a')
    
    - 写数据

    f = open('file.txt', 'w')
    f.write(all_the_text)
    f.close( )
    

with语句

with open('file.txt') as f=:
    c = f.read()
with语句类似

try :
    ……
except:
    ……
finally:
    ……

nested函数

with nested(A(), B(), C()) as (X, Y, Z):
    ……
等同于
with A() as X:
    with B() as Y:
        with C() as Z:
            ……

逐行读取

  • for ... in ...
    with open("file") as fh:
        for line in fh:
            print(line.strip())
    
  • while fh.readline():
    with open("file") as fh:
        line = fh.readline()
        while line:
            print(line.strip())
            line = fh.readline()