欢迎访问宙启技术站
智能推送

Python中的路径文件属性获取方法

发布时间:2024-01-14 16:32:11

在Python中,可以使用os模块提供的方法来获取文件的属性。以下是获取文件属性的几种方法以及使用示例:

1. 获取文件大小:

可以使用os.path.getsize()函数来获取文件的大小(字节数)。例如:

import os

file_path = 'C:/path/to/file.txt'
file_size = os.path.getsize(file_path)
print(f"File size: {file_size} bytes")

2. 获取文件创建时间:

可以使用os.path.getctime()函数来获取文件的创建时间(以秒为单位)。例如:

import os
import time

file_path = 'C:/path/to/file.txt'
file_ctime = os.path.getctime(file_path)
file_ctime_str = time.ctime(file_ctime)
print(f"File creation time: {file_ctime_str}")

3. 获取文件修改时间:

可以使用os.path.getmtime()函数来获取文件的修改时间(以秒为单位)。例如:

import os
import time

file_path = 'C:/path/to/file.txt'
file_mtime = os.path.getmtime(file_path)
file_mtime_str = time.ctime(file_mtime)
print(f"File modification time: {file_mtime_str}")

4. 获取文件访问时间:

可以使用os.path.getatime()函数来获取文件的访问时间(以秒为单位)。例如:

import os
import time

file_path = 'C:/path/to/file.txt'
file_atime = os.path.getatime(file_path)
file_atime_str = time.ctime(file_atime)
print(f"File access time: {file_atime_str}")

5. 获取文件权限:

可以使用os.access()函数来检查文件的权限。例如,通过使用os.R_OKos.W_OKos.X_OK来检查文件是否可读、可写和可执行。例如:

import os

file_path = 'C:/path/to/file.txt'

if os.access(file_path, os.R_OK):
    print("File is readable")
else:
    print("File is not readable")

if os.access(file_path, os.W_OK):
    print("File is writable")
else:
    print("File is not writable")

if os.access(file_path, os.X_OK):
    print("File is executable")
else:
    print("File is not executable")

上述例子中,根据文件路径使用os.access()函数检查文件是否可读、可写和可执行。

除了上述的文件属性获取方法外,还可以使用os.path模块提供的其他方法来获取文件的不同属性,如文件名、目录名等。

希望这些例子能够帮助你理解在Python中获取文件属性的方法。