问题
I have a for loop inside which I print each iterations in the loop and gives a output that is in the format of ls-lrt . I would like to create a dictionary out of this with key as name of file and value as the timestamp.
for attr in sftp.listdir_attr('/abc'):
... print attr
...
-rwxr-xr-x 1 7202711 7201853 5759 01 Mar 12:49 .nfs0000000615c569f500000004
-rw-r--r-- 1 7202711 7201853 62394 26 Sep 2017 1.java
-rwxr-xr-x 1 7202711 7201853 5009 20 Aug 2017 a.sh
-rwxr-xr-x 1 7202711 7201853 2201 15 Oct 2017 adt.sh
drwxr-xr-x 1 7202711 7201853 282 09 Jun 2017 backup
-rwxr-xr-x 1 7202711 7201853 1384 27 Jul 2017 ob.sh
If I do a
type(attr)
it gives me
<class 'paramiko.sftp_attr.SFTPAttributes'>
So the dict should be like (the date and time format needs to be standardized)
{'.nfs0000000615c569f500000004':'01 Mar 12:49',
'1.java':'26 Sep 2017',..............etc}
回答1:
SFTPClient.listdir_attr actually returns a list of SFTPAttrributes objects. It's likely you can access the filename and timestamp of the last modification as attr.filename
and attr.st_mtime
(You'll likely need to convert this from a timestamp into a human readable date). Unfrtunately, these objects seem to be created based on the results of os.stat
, which don't always return the same thing across operating systems. You should experiment with all the system types you plan to use this software on.
回答2:
It seems listdir_attr()
output also depends on the underlying server implementation. If you already have the printable format you can try splitting the values by \t
may be use the last splitted value to be your key and second last would be your value. Also you can load the data in pandas dataframe and can directly access the fields you need with column names.
回答3:
Here is what you can do
from collections import defaultdict
temp = defaultdict()
for file in sftp.listdir(PATH):
temp[file].append(sftp.lstat(file)[X]) # where X is the column you want for as your value
回答4:
Do something like this
from time import gmtime, strftime
Be sure to import these
d = {}
for attr in sftp.listdir_attr('/abc'):
time_structer = gmtime(attr.st_mtime)
d[attr.filename] = strftime("%a, %d %b %Y %H:%M:%S", time_structer)
来源:https://stackoverflow.com/questions/50139901/create-dictionary-from-a-print-output-in-python