0

我试图连接目录中的所有 txt 文件,同时删除不需要的第一行,但我似乎没有找到按时间戳顺序联系文件的方法,文件名也代表所需的顺序。

import os

switch = True;
for file in os.listdir(os.getcwd()):
    if file.endswith(".txt"):
        print(file)
        with open(file, 'r') as fin:
            dt = fin.read().splitlines(True)
            with open(os.path.join(os.getcwd(), 'filename.txt'), 'a') as fout:
                if switch == True:
                    fout.writelines(dt[5:])
                    switch = False;
                elif switch == False:
                    fout.writelines(dt[5:])


output:

Sensors.20210209100733.txt
Sensors.20210209025203.txt
Sensors.20210209042850.txt
Sensors.20210209002654.txt
Sensors.20210209020340.txt
Sensors.20210209011517.txt
Sensors.20210208211320.txt
Sensors.20210209034027.txt
Sensors.20210208184810.txt
Sensors.20210208171124.txt
Sensors.20210208193634.txt
Sensors.20210209060537.txt
Sensors.20210208175947.txt
Sensors.20210209074223.txt
Sensors.20210209051713.txt
Sensors.20210208233830.txt
Sensors.20210209083047.txt
Sensors.20210209091910.txt
Sensors.20210208225007.txt
Sensors.20210208202457.txt
Sensors.20210208220144.txt
Sensors.20210209065400.txt

所需订单:

第一个文件 - Sensors.20210208171124 ..datetime order... 最后一个文件 - Sensors.20210209100733

谢谢!

4

1 回答 1

0

假设您已经在列表中有文件名,您可以将该sorted方法与自定义方法一起使用,该方法按文件名中的日期排序为:

x = ["Sensors.20210209100733.txt", "Sensors.20210209025203.txt", 
     "Sensors.20210209042850.txt", "Sensors.20210209002654.txt",
     "Sensors.20210209020340.txt", "Sensors.20210209011517.txt",
     "Sensors.20210208211320.txt", "Sensors.20210209034027.txt",
     "Sensors.20210208184810.txt", "Sensors.20210208171124.txt",
     "Sensors.20210208193634.txt", "Sensors.20210209060537.txt",
     "Sensors.20210208175947.txt", "Sensors.20210209074223.txt",
     "Sensors.20210209051713.txt", "Sensors.20210208233830.txt"]

from dateutil.parser import parse

def date_from_name(name):
    return parse(name.split('.')[-2])
    
sorted_list = sorted(x, key=date_from_name)
print(sorted_list)

输出:

['Sensors.20210208171124.txt', 'Sensors.20210208175947.txt', 'Sensors.20210208184810.txt', 'Sensors.20210208193634.txt', 'Sensors.20210208211320.txt', 'Sensors.20210208233830.txt', 'Sensors.20210209002654.txt', 'Sensors.20210209011517.txt', 'Sensors.20210209020340.txt', 'Sensors.20210209025203.txt', 'Sensors.20210209034027.txt', 'Sensors.20210209042850.txt', 'Sensors.20210209051713.txt', 'Sensors.20210209060537.txt', 'Sensors.20210209074223.txt', 'Sensors.20210209100733.txt']
于 2021-02-09T11:39:28.500 回答