根据文件名列表创建文本文件

我在 filenames.txt 中有一个文件名列表,其中包含两个或多个文件,日期如下:


foo_19990101_bar001.zip

foo_19990101_bar002.zip

foo_20000303_bar001.zip

foo_20000303_bar002.zip

foo_20000303_bar003.zip

foo_20021111_bar001.zip

foo_20021111_bar002.zip

...

我想创建单独的文本文件,其中包含单个日期的文件名,例如 19990101.txt 将包含:


foo_19990101_bar001.zip

foo_19990101_bar002.zip

谢谢您的帮助!


慕的地8271018
浏览 227回答 2
2回答

婷婷同学_

你可以试试这个:#!/bin/bashwhile read -r line; do&nbsp; &nbsp; date="${line:4:8}"&nbsp; &nbsp; echo "$line" >> "${date}.txt"done < filenames.txt

ibeautiful

这将创建名称作为时间戳的新文件。from collections import defaultdictwith open("filenames.txt") as fp:&nbsp; &nbsp; file_names = fp.read().split()&nbsp; &nbsp;&nbsp;files_dict = defaultdict(list)for name in file_names:&nbsp; &nbsp; timestamp = name.split("_", 2)[1]&nbsp; &nbsp; files_dict[timestamp].append(name)for key, value in files_dict.items():&nbsp; &nbsp; with open(key, "w") as fp:&nbsp; &nbsp; &nbsp; &nbsp; fp.write("\n".join(value))
打开App,查看更多内容
随时随地看视频慕课网APP

相关分类

Python