I’m very new to python, and I’d like to know how I can use the info in a text file to create variables. For example, if the txt file looked like this:
vin_brand_type_year_price
2132_BMW_330xi_2016_67000
1234_audi_a4_2019_92000
9876_mclaren_720s_2022_327000
How do I then, for example, use it to make a variable called vin and have all the vin numbers in it?
I can have the terminal read it. this is what i have so far
with open('car.txt', 'r') as file:
file_content = file.read()
print(file_content)
>Solution :
Here is a method to make a dict of the values and treat the first row as the header:
with open(your_file) as f:
header=[e.strip() for e in next(f).split('_')]
data={}
for row in f:
for k, v in zip(header, [e.strip() for e in row.split('_')]):
data.setdefault(k, []).append(v)
Result:
>>> data
{'vin': ['2132', '1234', '9876'], 'brand': ['BMW', 'audi', 'mclaren'], 'type': ['330xi', 'a4', '720s'], 'year': ['2016', '2019', '2022'], 'price': ['67000', '92000', '327000']}