首页
学习
活动
专区
工具
TVP
发布
精选内容/技术社群/优惠产品,尽在小程序
立即前往

如何在Python中从cwd中获取单个文件大小

在Python中,可以使用os模块来获取当前工作目录(cwd)中单个文件的大小。具体步骤如下:

  1. 导入os模块:
代码语言:txt
复制
import os
  1. 使用os.path.join()函数将当前工作目录和文件名拼接为完整的文件路径:
代码语言:txt
复制
file_path = os.path.join(os.getcwd(), '文件名')

其中,将文件名替换为你要获取大小的文件名。

  1. 使用os.path.getsize()函数获取文件的大小,单位为字节:
代码语言:txt
复制
file_size = os.path.getsize(file_path)
  1. 如果需要将文件大小转换为其他单位(如KB、MB、GB等),可以使用以下函数进行转换:
代码语言:txt
复制
def convert_size(size):
    # 1 KB = 1024 bytes
    # 1 MB = 1024 KB
    # 1 GB = 1024 MB
    units = ['bytes', 'KB', 'MB', 'GB']
    index = 0
    while size >= 1024 and index < len(units) - 1:
        size /= 1024
        index += 1
    return f"{size:.2f} {units[index]}"

然后,调用convert_size()函数将文件大小转换为所需单位:

代码语言:txt
复制
file_size_formatted = convert_size(file_size)

完整的代码如下:

代码语言:txt
复制
import os

def convert_size(size):
    units = ['bytes', 'KB', 'MB', 'GB']
    index = 0
    while size >= 1024 and index < len(units) - 1:
        size /= 1024
        index += 1
    return f"{size:.2f} {units[index]}"

file_path = os.path.join(os.getcwd(), '文件名')
file_size = os.path.getsize(file_path)
file_size_formatted = convert_size(file_size)

print(f"文件大小为:{file_size_formatted}")

这样,你就可以在Python中从当前工作目录中获取单个文件的大小了。

页面内容是否对你有帮助?
有帮助
没帮助

相关·内容

没有搜到相关的合辑

领券