常规我们所使用的方法是os.path.getsize(),今天见到一个写法是使用os.lseek()函数的方法。于是就特地查了查,然后顺便搞清楚喽。
(1)首先上代码看看lseek是如何使用的:
def file_size(filename):
'''
获取给定文件的大小
@filename - 文件的路径
Returns 文件的大小
'''
# Using open/lseek works on both regular files and block devices
fd = os.open(filename, os.O_RDONLY)
try:
return os.lseek(fd, 0, os.SEEK_END)
except KeyboardInterrupt as e:
raise e
except Exception as e:
raise Exception("file_size failed to obtain the size of '%s': %s" % (filename, str(e)))
finally:
os.close(fd)
lseek()方法语法格式如下:
os.lseek(fd, pos, how)
-
fd -- 文件描述符。
-
pos -- 这是相对于给定的参数 how 在文件中的位置。。
-
how -- 文件内参考位置。SEEK_SET 或者 0 设置从文件开始的计算的pos; SEEK_CUR或者 1 则从当前位置计算; os.SEEK_END或者2则从文件尾部开始。
其中how所对应的参数的话:
- os.SEEK_SET或者0 :设置文件开始的计算的pos
- os.SEEK_CUR 或者1:从当前位置开始计算
- os.SEEK_END或者2:从文件尾部开始计算
SEEK_SET 将读写位置指向文件头后再增加offset个位移量。
SEEK_CUR 以目前的读写位置往后增加offset个位移量。
SEEK_END 将读写位置指向文件尾后再增加offset个位移量。
当whence 值为SEEK_CUR 或SEEK_END时,参数offet允许负值的出现。
下列是较特别的使用方式:
1) 欲将读写位置移到文件开头时:
lseek(int fildes,0,SEEK_SET);
2) 欲将读写位置移到文件尾时:
lseek(int fildes,0,SEEK_END);
3) 想要取得目前文件位置时:
lseek(int fildes,0,SEEK_CUR);
(2)然后我们来比较一下os.sleek()和os.path.getsize()的区别
# -*- coding:utf-8 -*-
# @Author:zgd
# @time:2019/7/29
# @File:test2.py
import os
filename = "/home/ubuntu/zgd/ztest/gs418_510txp_v6.6.2.7.stk"
fopen = os.open(filename, os.O_RDONLY)
fsize = os.lseek(fopen, 0, os.SEEK_END)
fsize2 = os.path.getsize(filename)
print fsize
print fsize2
输出结果:
19681843
19681843
由上面可以看出,输出的结果是一致的,都是以字节的形式输出,输出的字节数相同。
参考链接:
https://blog.youkuaiyun.com/qq_41660466/article/details/81381532
https://www.runoob.com/python/python-func-super.html