我试图连接目录中的所有 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
谢谢!