【问题标题】:Python mapping all files inside a folderPython映射文件夹内的所有文件
【发布时间】:2013-08-29 12:14:36
【问题描述】:

您好,我正在编写一个 Python 脚本,它将映射到一个列表(或任何其他对象),并且列表的每个单元格中都有 6 个项目:

  1. 文件路径。
  2. 文件名(不含完整路径)。
  3. 扩展名。
  4. 创建时间。
  5. 上次修改时间。
  6. 这是 md5 哈希。

我对python有点陌生,我尝试了我所知道的一切......

有什么帮助吗?

谢谢:)

【问题讨论】:

  • “我对python有点陌生,我尝试了我所知道的一切......”你尝试了什么?什么失败了?
  • 我现在不在我的电脑上......但我相信我的知识,坦率地说,我所做的一切都不值得......
  • @pyDan -- 即使你认为你的尝试不值得谈论,你仍然应该在这里发布它们。 StackOverflow 上的人往往会做出消极回应,因为提问者似乎没有努力尝试自己解决问题。应对这种情况的最佳方法是始终包含您尝试过的内容、引发的错误等。另外,如果您展示您的代码,StackOverflow 上的人们可以更好地了解您的错误是什么,您正在尝试什么做,并提供一般有用的提示。

标签: python file list mapping directory


【解决方案1】:

哦,来吧,继续谷歌搜索“python显示文件信息”出现的第一件事是:

Getting Information About a File

This function takes the name of a file, and returns a 10-member tuple with the following contents:

(mode, ino, dev, nlink, uid, gid, size, atime, mtime, ctime)

然后你去python的文档,你会发现参数是什么意思:

os.stat

st_mode - protection bits,
st_ino - inode number,
st_dev - device,
st_nlink - number of hard links,
st_uid - user id of owner,
st_gid - group id of owner,
st_size - size of file, in bytes,
st_atime - time of most recent access,
st_mtime - time of most recent content modification,
st_ctime - platform dependent; time of most recent metadata change on Unix, or the time of creation on Windows)

那你去看看如何列出一个dir函数,这也在名为listdir的文档中。不要告诉我这很难,我花了 1 分钟。

这是使用 DFS(深度优先搜索)遍历槽文件夹的方法:

import os 

def list_dir(dir_name, traversed = [], results = []): 
    dirs = os.listdir(dir_name)
    if dirs:
        for f in dirs:
            new_dir = dir_name + f + '/'
            if os.path.isdir(new_dir) and new_dir not in traversed:
                traversed.append(new_dir)
                list_dir(new_dir, traversed, results)
            else:
                results.append([new_dir[:-1], os.stat(new_dir[:-1])])  
    return results

dir_name = '../c_the_hard_way/Valgrind/' # sample dir
for file_name, stat in list_dir(dir_name):
    print file_name, stat.st_size # sample with file size

剩下的交给你。

【讨论】:

  • 相信我,我尝试了很多方法,但总是有问题。我想你误解了我,对我来说最难的部分是如何映射所有文件。最简单的部分是获取状态。
  • 试试我的代码,但你需要为文件使用另一个数组。
  • 首先,感谢您的帮助!非常感谢。几秒钟,我有点理解你在这个脚本中做了什么,但是,我对 python 不太擅长,你的帮助很好,真的提高了我对 python 的理解和练习.. 你能告诉我如何添加数组有统计数据?我希望你能得到你对我的帮助 :) 再次感谢 :)
  • 好吧,我更新了代码,但是如果您认为自己不擅长 python,请尝试阅读 learnpythonthehardway.org/book
  • 太棒了!厉害了我的朋友
猜你喜欢
  • 2021-09-30
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2017-02-07
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 2015-06-19
相关资源
最近更新 更多