There is a data.txt text file in the following format (the length of the text file can be any length):
Start 111 139
A 122 155
B 133 217
C 144 223
Finish
The delimiter character between each value is a tabulator (\t), and the rows are ended with enters (\n). I would like to put each value into a separate variable with the correct type (int for numbers, string for texts). The length of the text file can be any length (D, E, F... rows with different numbers can be there). In the last row there is always one word: "Finish". For the example above I would like to get 5 string variables and 8 int variables overall. The ideal output would be the following:
str1 = str('Start')
int1 = int(111)
int2 = int(139)
str2 = str('A')
int3 = int(122)
int4 = int(155)
str3 = str('B')
int5 = int(133)
int6 = int(217)
str4 = str('C')
int7 = int(144)
int8 = int(223)
str5 = str('Finish')
The name of the variables can be anything, and also the cast is not required if your method already defines the type of the variables.
For the reading in parts I tried this:
with open('data.txt') as file:
lines = [line.rstrip().split('\t') for line in file]
print(lines)
But it gives me lists of threes, however, I would like to create separate variables for each value dynamically. Thank you for your help in advance!
CodePudding user response:
Your example does not really make sense. But, if that is what you are looking for:
def conv(s):
try:
return ('int', int(s))
except ValueError:
return ('str', f"'{s}'")
cnt={}
with open('/tmp/file') as f:
for line in f:
for s in line.split():
t=conv(s)
cnt[t[0]]=cnt.get(t[0], 0) 1
print(f'{t[0]}{cnt[t[0]]} = {t[0]}({t[1]})')
Prints:
str1 = str('Start')
int1 = int(111)
int2 = int(139)
str2 = str('A')
int3 = int(122)
int4 = int(155)
str3 = str('B')
int5 = int(133)
int6 = int(217)
str4 = str('C')
int7 = int(144)
int8 = int(223)
str5 = str('Finish')
DON'T try and make variables out of these! Instead, use a dict
like so:
def conv(s):
try:
return ('int', int(s))
except ValueError:
return ('str', f"'{s}'")
cnt={}
data={}
with open('/tmp/file') as f:
for line in f:
for s in line.split():
t=conv(s)
cnt[t[0]]=cnt.get(t[0], 0) 1
data[f'{t[0]}{cnt[t[0]]}'] = t[1]
>>> data
{'str1': "'Start'", 'int1': 111, 'int2': 139, 'str2': "'A'", 'int3': 122, 'int4': 155, 'str3': "'B'", 'int5': 133, 'int6': 217, 'str4': "'C'", 'int7': 144, 'int8': 223, 'str5': "'Finish'"}