I have been trying to extract data from a txt file
This is the text file:
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
I want to extract some information from the text file to get this information
WeekNumber= 31
5.8.6.32NUMBER2319
This is how I tried to do it:
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)
The errors I have received:
> buildnumber = secondhalf[2] + "NUMBER" + secondhalf[3]
>IndexError: string index out of range
and
> datetime.date(date).isocalendar()[1]
>TypeError: an integer is required (got type tuple)
I am fairly new to python so any assistance would be greatly appreciated
You can use re
to get desired numbers. For the second error, use asterisk *
to unpack the tuple:
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))
Prints:
WeekNumber= 31
5.8.6.32NUMBER2319
EDIT: (To read from file):
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))
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.