我一直在对此问题进行一些研究,但我无法根据自己的问题来解决。
我想在目录中创建一个文件列表的文本文件,按日期排序,但是我不希望日期显示在文件中。 到目前为止,我的代码是:
#create list of clips to merge
save_path = 'downloads/'
ignored = 'test.bat','mergeclips.bat','draw.bat'
onlyfiles = [f for f in listdir('downloads/') if isfile(join('downloads/', f)) if f not in ignored]
with open('downloads/clipstomerge.txt', 'w') as f:
for item in onlyfiles:
f.write("file '%s'\n" % item )
此代码将忽略bat文件,但将其他所有内容以ffmpeg可以合并剪辑的格式列出到文本文件中。文本文件的格式如下:
file 'ARandomClipName.mov'
file 'Butterflies.mov'
file 'Chickens.mov'
目前,文件按字母顺序排序,但我希望按创建日期排序。 有谁知道如何修改代码以解决问题?
答案 0 :(得分:1)
我将使用os模块的listdir()和getcttime()功能以及列表理解,通过以下方式解决此问题。如下:
combo = [(os.path.getctime(x), x) for x in os.listdir()]
combo
Out[42]:
[(1549321055.8699787, 'AncmtNavSecLevPageResources_en.pov'),
(1549321046.853063, 'AncmtNavSecLevPageResources_es_US.pov'),
(1549321055.8855789, 'EcsNavSecLevPageResources_es_US.pov'),
(1549321047.3054688, 'GlobalNavFlyOutResources.pov'),
(1549321046.8842635, 'GlobalNavFlyOutResources_en.pov'),
(1549321046.4942584, 'GlobalNavFlyOutResources_es_US.pov'),
(1549321046.5254588, 'WebChatAvailResources.pov'),
(1549321047.2430682, 'WebChatAvailResources_es_US.properties')]
现在,如果需要阻止.bat文件,则可以使用以下条件:
combo = [(os.path.getctime(x), x) for x in os.listdir() if '.properties' not in x]
combo
Out[45]:
[(1549321055.8699787, 'AncmtNavSecLevPageResources_en.pov'),
(1549321046.853063, 'AncmtNavSecLevPageResources_es_US.pov'),
(1549321055.8855789, 'EcsNavSecLevPageResources_es_US.pov'),
(1549321047.3054688, 'GlobalNavFlyOutResources.pov'),
(1549321046.8842635, 'GlobalNavFlyOutResources_en.pov'),
(1549321046.4942584, 'GlobalNavFlyOutResources_es_US.pov'),
(1549321046.5254588, 'WebChatAvailResources.pov')]
然后只需使用sort()函数对列表进行排序(在这种情况下为ergo combo.sort())。此时,您只需按顺序打印列表即可。哪个应该根据文件的创建日期放置文件。
如何将其应用于原始代码
import os
save_path = 'C:\Python37' #here you need to enter the FULL path for your folder
os.chdir(save_path)
combo = [(os.path.getctime(x), x) for x in os.listdir() if '.bat' not in x]
combo.sort() #will sort the index, which is the created timestamp
with open("targetFile.txt", 'w') as f:
for file in range(0, len(combo)):
f.write('file: ' + combo[file][1] + '\n')
此处的组合变量包含以下内容:
[(1547253963.0511992, 'LearnPythonEx4.py'),
(1547253963.0862029, 'LearnPythonEx5.py'),
(1547253963.1162057, 'LearnPythonEx6.py'),
(1547253963.137208, 'LearnPythonEx7.py'),
(1547253964.490343, 'LICENSE.txt'),
(1547253965.6564598, 'NEWS.txt'),
(1547253966.5165458, 'python.exe'),
(1547253966.5725515, 'python3.dll'),
(1547253966.8515792, 'python37.dll'),
(1547253966.9225864, 'pythonw.exe'),
(1547253967.0145955, 'vcruntime140.dll')]
示例文件内容:
file: LearnPythonEx4.py
file: LearnPythonEx5.py
file: LearnPythonEx6.py
file: LearnPythonEx7.py
file: LICENSE.txt
file: NEWS.txt
file: python.exe
file: python3.dll
file: python37.dll
file: pythonw.exe
file: vcruntime140.dll