首页 > 解决方案 > 使用日期控制中断逻辑

问题描述

我很难弄清楚如何读取文本文件的多行并产生所需的输出。我尝试了日期时间格式,但它不会去任何地方。我将不胜感激任何帮助

所要求的是: 写照片报告 - 对于项目的这一部分,我们将获取一个数据文件并在其上使用控制中断逻辑来生成屏幕报告。控制中断将在文件创建的年份。数据文件将具有以下格式(每行一个字段):

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

标签: pythonpython-3.xtkinter

解决方案


您可以使用内置模块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 

推荐阅读