我的公司希望从我们的旧商店过渡到PDM。我编写了一个脚本,该脚本将遍历目录并记录根目录、目录和文件。
我已经能够遍历目录并执行我希望能够对根、目录和文件执行的操作,并导出/排序/任何数据。但是我希望能够获得创建日期st_ctime
和修改日期st_mtime
。我在网上找到了可以做一个目录的解决方案,但我想把它实施到我当前的os.walk()
中。
我的目标是,就像我对根、目录和文件所做的那样,是获取 ctime、mtime 并将其附加到一个列表中,我可以将其连接到数据帧中,然后按照我想要的方式进行操作。我只是不知道如何获得它。
下面是我的代码。如何获取ctime
和mtime
并将它们附加到相应的列表中?
编辑:我正在使用Windows 10
global path_to_crawl
self.c = 0
self.roots_list = ['Roots']
self.dirs_list = ['Dirs']
self.files_list = ['Files']
self.ctime_list = ['Date Created']
self.mtime_list = ['Date Modified']
self.selection_to_output_df = pd.DataFrame({})
for (root, dirs, files) in os.walk(path_to_crawl):
self.roots_list.append(root)
self.dirs_list.append(dirs)
self.files_list.append(files)
### HOW TO GET ctime AND APPEND IT TO self.ctime_list? ###
### HOW TO GET mtime AND APPEND IT TO self.mtime_list? ###
self.c += 1
roots_df = pd.DataFrame({'Roots': self.roots_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, roots_df], axis=1)
dirs_df = pd.DataFrame({'Dirs': self.dirs_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, dirs_df], axis=1)
files_df = pd.DataFrame({'Files': self.files_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, files_df], axis=1)
您可能想调用os.stat
。类似的东西
stats = [os.stat(os.path.join(root, file)) for file in files]
self.ctime_list.append([stat.st_ctime for stat in stats])
self.mtime_list.append([stat.st_mtime for stat in stats])
,我在网上找到了一个示例,并对其进行了一些调整以适应我的代码:
global path_to_crawl
self.c = 0
self.files_list = ['File Path']
self.ctime_list = ['Date Created']
self.mtime_list = ['Date Modified']
self.selection_to_output_df = pd.DataFrame({})
for root, _, filenames in os.walk(path_to_crawl):
for filename in filenames:
file_path = root + '/' + filename
created = os.path.getctime(file_path)
modified = os.path.getmtime(file_path)
self.files_list.append(file_path)
self.ctime_list.append(time.ctime(created))
self.mtime_list.append(time.ctime(modified))
self.c += 1
files_df = pd.DataFrame({'File Path': self.files_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, files_df], axis=1)
created_df = pd.DataFrame({'Date Created': self.ctime_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, created_df], axis=1)
modified_df = pd.DataFrame({'Date Modified': self.mtime_list[1:]})
self.selection_to_output_df = pd.concat([self.selection_to_output_df, modified_df], axis=1)
self.all_files_list = []
for sublist in self.files_list[1:]:
for item in sublist:
self.all_files_list.append(item)
return self.selection_to_output_df