错误代码
原代码
import os
count = 0
size = os.path.getsize("G:\stduentfile\模块练习")
with open("模块练习","r",encoding="utf-8") as f:
while count < size:
line = f.read()
print(line)
count += len(line)
这样写,导致遍历停不下来
注意:
用文件file_size = os.path.getsize()
来判断文件长度
size = os.path.getsize()
是一样的
但是len(f.read())
得出的结果与上面不一样
注意,读取文件的时候,要用len计算字符串长度来计算文件大小,因为这两个结果不一样,这是错误的行为一般最好用for in 迭代文件对象
修改后代码
import os
count = 0
size = os.path.getsize("G:\stduentfile\模块练习")
with open("模块练习","r",encoding="utf-8") as f:
while f.tell() < size:
line = f.read()
print(line)