如何使用Python获取文件系统信息?

如何使用Python获取文件系统信息?

在Python中,我们可以通过os模块来获取文件系统信息,包括文件大小、访问时间、修改时间等。

阅读更多:Python 教程

查看当前工作目录

使用os.getcwd()函数可以获取当前工作目录:

import os

current_dir = os.getcwd()
print(current_dir)

运行上述代码后,会输出当前工作目录的路径。

获取文件大小

使用os.path.getsize()函数可以获取文件的大小,返回的单位是字节:

import os

file_path = "example.txt"
file_size = os.path.getsize(file_path)
print("文件大小为{}字节".format(file_size))

在上述代码中,我们获取了名为example.txt文件的大小。

获取文件访问时间和修改时间

使用os.path.getatime()os.path.getmtime()函数可以获取文件的访问时间和修改时间:

import os
import time

file_path = "example.txt"
access_time = os.path.getatime(file_path)
modify_time = os.path.getmtime(file_path)

access_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(access_time))
modify_time_str = time.strftime("%Y-%m-%d %H:%M:%S", time.localtime(modify_time))

print("文件访问时间为:{}".format(access_time_str))
print("文件修改时间为:{}".format(modify_time_str))

在上述代码中,我们获取了名为example.txt文件的访问时间和修改时间,并将其转换为可读的时间格式。

获取磁盘空间信息

使用os.statvfs()函数可以获取文件系统的空间信息,包括总空间、可用空间、已使用空间等:

import os

path = "/"
statvfs = os.statvfs(path)

total_space = statvfs.f_blocks * statvfs.f_bsize
free_space = statvfs.f_bfree * statvfs.f_bsize
used_space = (statvfs.f_blocks - statvfs.f_bfree) * statvfs.f_bsize

print("磁盘总空间为{}字节".format(total_space))
print("磁盘可用空间为{}字节".format(free_space))
print("磁盘已使用空间为{}字节".format(used_space))

在上述代码中,我们获取了根目录/的磁盘空间信息,并将总空间、可用空间、已使用空间分别输出。

结论

Python的os模块提供了获取文件系统信息的接口,通过这些接口,我们可以方便地获取文件信息、磁盘空间信息等。

Camera课程

Python教程

Java教程

Web教程

数据库教程

图形图像教程

办公软件教程

Linux教程

计算机教程

大数据教程

开发工具教程