如果要读取一个文件里的内容是
# 文件名:db.txt
1
2
3
4
代码如下
import requests
f = open("db.txt", mode="rb")
content = f.read()
f.close()
data = content.decode('utf-8')
# 存到 list 里
data_list = data.split('\r\n')
print(data_list)
# 结果如下
# ['1', '2', '3', '4']
也可以这么写
import requests
f = open("db.txt", mode="r", encoding="utf-8")
content = f.read()
f.close()
data_lst = content.split(',')
print(data_lst)
# 结果如下
['1', ' 2', ' 3', ' 4']
如果读取的文档是文本,就用
f = open("文件路径", mode='r', encoding='utf-8')
content = f.read()
f.close()
如果要读取 图片/视频/gif 文件,就用
f = open("文件路径”,mode="rb')
data = f.read()
f.close()
如果要读取大文件,比如100G。代码例子如下
import requests
f = open("db.txt", mode="r", encoding="utf-8")
for line in f:
line = line.strip()
if not line:
continue
print(line)
f.close()
如果要下载mp3文件,大小1000G,代码例子如下
import os
# 文件总大小
totalSize = os.stat("db.txt").st_size
f = open("db.txt", mode='rb')
hasReadSize = 0
while hasReadSize <= totalSize:
part = f.read(4) # 读4个字节
hasReadSize += len(part)
f.close()
使用 with 来打开文件
with open("db.txt", mode="r", encoding="utf-8") as f:
content = f.read()
print(content)
# with 是为了防止忘记写 f.close()
上面的对应下面
f = open("db.txt", mode="r", encoding="utf-8")
content = f.read()
f.close()
print(content)
给个赞呗~