Извлечение разных данных из txt файла в python - PullRequest
1 голос
/ 06 августа 2020

Я пытался извлечь данные из текстового файла

Это текстовый файл:

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, поэтому буду благодарен за любую помощь

1 Ответ

0 голосов
/ 06 августа 2020

Вы можете использовать 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

EDIT: (для чтения из файла):

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))
...