python - 使用日期控制中断逻辑
问题描述
我很难弄清楚如何读取文本文件的多行并产生所需的输出。我尝试了日期时间格式,但它不会去任何地方。我将不胜感激任何帮助
所要求的是: 写照片报告 - 对于项目的这一部分,我们将获取一个数据文件并在其上使用控制中断逻辑来生成屏幕报告。控制中断将在文件创建的年份。数据文件将具有以下格式(每行一个字段):
Date Created (in the form DD-MM-YYYY) Filename
Number of Bytes
例如,以下输入文件:
25-02-2019
MyTurtle.GIF
6000
11-05-2019
Smokey.GIF
4000
我无法读取和输出文件中的日期。我目前拥有的是:
def openFile(self):
myFile = self.inputFile.getText()
fileName = open(myFile, "r")
text = fileName.readline()
x = "%4s%25s%25s\n\n" % ("File Name", "Date Created", "Number of Bytes")
date_str_format = '%Y-%m-%d'
jobs = []
for i in fileName:
d = datetime.strptime(i[0],'%m-%d-%Y')
if d in i:
date = i
x += "%4d\n" % date
解决方案
您可以使用内置模块re
从文件中提取所有文件名、日期和字节:
import re
from datetime import datetime
with open('file.txt', 'r') as f:
t = f.read()
dates = re.findall('\d\d-\d\d-\d\d\d\d', t) # Find all the dates in the form of 00-00-0000
files = re.findall('\w+\.\w+', t) # Find all the file names in the form of text.text
byte = re.findall('(?<!-)\d\d\d\d', t) # Find all the number of bytes in the for of a four digit number without a dash behind it
print("File Name".ljust(15), "Date Created".ljust(15), "Number of Bytes".ljust(15))
for d, f, b in zip(dates, files, byte):
print(f.ljust(15), d.ljust(15), b.ljust(15))
输出:
File Name Date Created Number of Bytes
MyTurtle.GIF 25-02-2019 6000
Smokey.GIF 11-05-2019 4000
推荐阅读
- json - 在 VB.NET 中从 JSON 中的数组获取属性
- flutter - Flutter Unhandled 异常:在绑定初始化之前访问了 ServicesBinding.defaultBinaryMessenger
- sql - 将所有子记录中的列合并为一列
- unity3d - HoloLens 2 无法连接到服务器
- javascript - 角度组件变量返回未定义
- ios - 在位于滚动视图上方的 SwiftUI 视图上使用 .shadow 修饰符,当其他视图重叠时可以看到可见的阴影线
- python - 按枢轴值Python对数据透视表进行排序
- amazon-s3 - S3 Bucket Stage 上的正则表达式 - 来自 Snowflake
- java - 什么是 Java 中的 std::variant
- azure-cognitive-search - 如何使用 Collection(Edm.String) 的现有“内容”字段索引 blob 内容?