【问题标题】:Python TypeError: coercing to Unicode: need string or buffer, posix.stat_result foundPython TypeError:强制转换为 Unicode:需要字符串或缓冲区,找到 posix.stat_result
【发布时间】:2013-10-18 09:07:13
【问题描述】:

我试图从文件夹中的文件中获取名称、上次访问日期和上次修改日期,一切正常。现在我尝试添加文件大小,但从那里我得到了这个错误。

我的工作结果没有尺寸:

[['28e20ee3-8e8c-427d-af73-cd9de58b5811_1156153318066-Ajax_Thuis_A4_665.jpg', 'Fri Oct 18 10:28:11 2013', 'Fri Oct 18 10:28:11 2013']]

我的代码是这样的

import os,time

def get_information(directory):
    file_list = []
    for i in os.listdir(directory):
        a = os.stat(os.path.join(directory,i))
        file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime)]) #[file,most_recent_access,created]
    return file_list

print get_information("/home/randy/testfolder")

我的大小代码如下所示(仅相关):

file_list.append([i,time.ctime(a.st_atime),time.ctime(a.st_ctime),os.path.getsize(a)])

如何让输出显示文件大小而没有错误?我需要对大量文件执行此操作。

【问题讨论】:

    标签: python string unicode buffer filesize


    【解决方案1】:

    你有

    a = os.stat(os.path.join(directory,i))
    os.path.getsize(a)
    

    os.path.getsize 将路径作为参数,但你给它的结果是os.stat

    您可以直接使用a.st_size,而不是调用os.path.getsize

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2021-03-28
      • 2015-02-01
      • 2014-12-21
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      • 1970-01-01
      相关资源
      最近更新 更多