如何将此列表存储为Django数据库中的单个数据?

时间:2013-01-04 06:33:05

标签: python django operating-system

我有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'

2 个答案:

答案 0 :(得分:1)

您只是传递了文件名(即'__init__.py'),而不是完整路径(即'/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

答案 1 :(得分:0)

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