0

我有这样的subprocess代码:

final_list = subprocess.Popen(['ls', destination], stdout=subprocess.PIPE).communicate()[0].splitlines()

这会将目录作为列表返回:

['genelaytics', '__init__.py', '__init__.pyc', 'settings.py', 'wsgi.pyc']

现在我想计算每个文件的大小并将文件作为单个元素连同大小和其他属性一起插入到数据库中。我尝试使用 for 循环:

for list in final_list:     
        st = os.stat(list)
        size = st.st_size 
        b = File(file_name=list, source=test_url, start_date=start_date, end_date=end_date, size=size)
        b.save()

运行上述代码时出现此错误:

Traceback:
File "/usr/local/lib/python2.6/dist-packages/django/core/handlers/base.py" in get_response
  111.                         response = callback(request, *callback_args, **callback_kwargs)
File "/usr/local/lib/python2.6/dist-packages/django/contrib/auth/decorators.py" in _wrapped_view
  20.                 return view_func(request, *args, **kwargs)
File "/home/zurelsoft/workspace/genelaytics/fileupload/views.py" in sync
  94.         st = os.stat(list)

Exception Type: OSError at /sync/
Exception Value: [Errno 2] No such file or directory: '__init__.py'
4

2 回答 2

1

您传递的只是文件名 (ie '__init__.py'),而不是完整路径 (ie '/module/__init__.py')os.stat()

我建议这样做:

>>> folder = '/Python27/Doc'
>>> files = os.listdir(folder)
>>> for filename in files:
    fullname = os.path.join(folder, filename)
    print fullname, os.path.getsize(fullname)


/Python27/Doc\python27.chm 5754439
于 2013-01-04T06:40:02.910 回答
0

在统计它之前,您需要将基本目录位置(os.dirname(__file__)...(可能))添加到文件名...

于 2013-01-04T06:36:51.867 回答