输入与输出--文件的读写

内建方法open常用的模式:open(filename, mode)
mode: w–>写, r–>读, a–>文件尾部追加, b–>二进制形式读写
默认只读:r

读取文件
写入“today is sunny\n”

f=open("./11.txt",'w')
f.write("today is sunny\n")      #字符串写入文件
f.close()                     #关闭文件
print(f.closed)         #文件是否关闭;关闭,返回True

追加文件
追加“I want to have a travel”

f=open("./11.txt",'a')
f.write("I want to have a travel")
f.close()

默认只读,二进制模式

with open("./11.txt") as f:     #模式默认只读:r
    s=f.read()
print(s)

with open("./11.txt",'rb') as f:     #模式默认只读:r
    s=f.read()
print(s)

输出:
输入与输出--文件的读写_第1张图片

读取完后,继续读为空
f.read()

with open("./11.txt",'r') as f:     
    s1=f.read()
    s2=f.read()
print(repr(s1))
print(repr(s2))

输出:
在这里插入图片描述

f.readline()

with open("./11.txt",'r') as f:     #模式默认只读:r
    s1=f.readline()
    s2=f.readline()
    s3=f.readline()
print(repr(s1))
print(repr(s2))
print(repr(s3))

输出:
在这里插入图片描述

f.read(size) 读取指定长度

with open("./11.txt",'r') as f:    
    s1=f.read(2)
print(repr(s1))

输出:‘to’

for line in f

with open("./11.txt",'r') as f: 
    for line in f:   #更高效
        print(repr(line))

输出:
‘today is sunny\n’
‘I want to have a travel’

获取所有行:list(f),f.readlines()

with open("./11.txt",'r') as f: 
    arr=list(f)
print(arr)

with open("./11.txt",'r') as f: 
    arr=f.readlines()
print(arr)

输出:
[‘today is sunny\n’, ‘I want to have a travel’]
[‘today is sunny\n’, ‘I want to have a travel’]

获取当前位置:f.tell()

with open("./11.txt",'r') as f: 
    f.read(2)
    print(f.tell())

输出:2

修改当前位置 f.seek(offset, from_what)
from_what :0–>开头 1–>当前位置 2–>结尾;默认0

with open("./11.txt",'r') as f: 
    f.seek(10)
    print(f.tell())

输出:10

你可能感兴趣的:(python)