Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

how to use info from .txt file to create variables in python?

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

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

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']}
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading