参考:https://github.com/geekcomputers/Python/blob/master/fileinfo.py
方法1 展示给定文件信息
(1) 使用f.readlines() 读取所有行数
(2) 使用os.path.getsize() 获取文件大小(B)
# -*- coding:utf-8 -*-
import os
import sys
def show_file_info(path):
""" show info for a give file"""
count = 0
with open(path) as f:
for line in f.readlines():
count = count + 1
print "count: ", count
size = os.path.getsize(path)
file_info = {
"file_name": path,
"file_line": count,
"file_size": size,
}
return file_info
def main():
""" main func """
path = os.getcwd() + '/thread.py'
print "path:", path
file_info = show_file_info(path)
print "file_info: ", file_info
if __name__ == '__main__':
main()
测试结果
file_info: {
'file_name': '/Users/xxx/PycharmProjects/xxx/thread.py',
'file_line': 23,
'file_size': 613
}
方法2 优化版本
使用
os.stat()
获取用于在给定的路径上执行一个系统 stat 的调用
# -*- coding:utf-8 -*-
import os
import sys
import stat
import time
def show_file_info(path):
""" show info for a give file"""
count = 0
with open(path) as f:
for line in f.readlines():
count = count + 1
print "count: ", count
statinfo = os.stat(path)
print "statinfo", statinfo
print type(statinfo)
file_info = {
"file_name": path,
"file_line": count,
"file_size": statinfo[stat.ST_SIZE],
"last_visit_time": statinfo[stat.ST_ATIME],
"last_modify_time": statinfo[stat.ST_MTIME],
"unix_time": statinfo[stat.ST_CTIME]
}
return file_info
def main():
""" main func """
path = os.getcwd() + '/thread.py'
print "path:", path
file_info = show_file_info(path)
print "file_info: ", file_info
if __name__ == '__main__':
main()
测试结果
file_info: {
'file_name': '/Users/xxx/PycharmProjects/xxx/thread.py',
'unix_time': 1574578332,
'last_modify_time': 1574578332,
'file_line': 23,
'file_size': 613,
'last_visit_time': 1574987036
}
网友评论