python之文件读取

1. 文件的四种模式:
r:指的是操作文本文件
rb:指的是操作非文本文件
r+,r+b,
2. 文件的读取的4种方式

read 全部读出来

f = open('读相对路径的文件',encoding='utf-8',mode='r')
content = f.read()
print(content,type(content))
f.close()

read(n)按照字符读取

f = open('读相对路径的文件',encoding='utf-8',mode='r')
content = f.read(2)  #按所占字符读取,空格也占字符
print(content)
f.close()

readline()#按行读取

f = open('读相对路径的文件',encoding='utf-8',mode='r')
print(f.readline())
f.close()
readlines()  #按多行读取:返回一个列表,列表中每一个元素是源文件的每一行
f = open('读相对路径的文件',encoding='utf-8',mode='r')
l1 = f.readlines()
print(l1)
f.close()

l1 = readlines()
for line in f :
    print(line)
    print (l1)
f.close()

for#循环读取

for line in f :
    print (line)
f.close()
posted @ 2021-12-01 15:28  哈哈妞儿  阅读(473)  评论(0)    收藏  举报