在python中从txt文件提取不同的数据

2024-09-24 02:25:39 发布

您现在位置:Python中文网/ 问答频道 /正文

我一直试图从txt文件中提取数据

这是文本文件:

PARTIALRUN,0
time,2020-07-31 12:21:44
update,5.8.6.32
build,2319
comments,testing
BaseDir,\\Testing\Python\2020_07_31_12_21_44

我想从文本文件中提取一些信息来获取这些信息

WeekNumber= 31
5.8.6.32NUMBER2319

我就是这样做的:

test_array =[]
with open ('file_location', 'rt') as testfile:
    for line in testfile:
        firsthalf, secondhalf =(
            item.strip() for item in line.split(',', 1))
        date = tuple(map(int, secondhalf.split('-')))
        datetime.date(date).isocalendar()[1]
        weekNumber= "Week Number: " + str(datetime.date(date).isocalendar()[1])
        print(workWeek)
        buildnumber = secondhalf[2] + "NUMBER" + secondhalf[3]
        print(buildnumber)  

我收到的错误:

>    buildnumber = secondhalf[2] + "NUMBER" + secondhalf[3]
>IndexError: string index out of range

>    datetime.date(date).isocalendar()[1]
>TypeError: an integer is required (got type tuple)

我是python的新手,因此非常感谢您的帮助


Tags: in信息fordatetimedatelineitemsplit
1条回答
网友
1楼 · 发布于 2024-09-24 02:25:39

您可以使用re获得所需的数字。对于第二个错误,请使用星号*解压元组:

import re
from datetime import date


txt = r'''PARTIALRUN,0
time,2020-07-31 12:21:44
update,5.8.6.32
build,2319
comments,testing
BaseDir,\\Testing\Python\2020_07_31_12_21_44'''

t = re.search(r'time,([^\s]+)', txt).group(1)
t = tuple(map(int, t.split('-')))
u = re.search(r'update,(.*)', txt).group(1)
b = re.search(r'build,(.*)', txt).group(1)

print('WeekNumber= {}'.format(date(*t).isocalendar()[1]))
print('{}NUMBER{}'.format(u, b))

印刷品:

WeekNumber= 31
5.8.6.32NUMBER2319

编辑:(从文件中读取):

import re
from datetime import date


with open('file_location', 'r') as f_in:
    txt = f_in.read()

t = re.search(r'time,([^\s]+)', txt).group(1)
t = tuple(map(int, t.split('-')))
u = re.search(r'update,(.*)', txt).group(1)
b = re.search(r'build,(.*)', txt).group(1)

print('WeekNumber= {}'.format(date(*t).isocalendar()[1]))
print('{}NUMBER{}'.format(u, b))

相关问题 更多 >