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

Question:

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)
Asked By: benova

||

Answers:

We can then use the index() method to find the index of the "vin" header in the list of header values. This will give us the index of the VIN number in each line of the text file. We can then use this index to extract

# Create an empty list to store the VIN numbers.
vin = []

# Open the text file and read its contents.
with open('car.txt', 'r') as file:
    # Read the first line of the file, which contains the header.
    header = file.readline()

    # Split the header on the underscore character.
    header_values = header.split("_")

    # Get the index of the "vin" header.
    vin_index = header_values.index("vin")

    # Read each line of the file, starting with the second line.
    for line in file:
        # Split the line on the underscore character.
        values = line.split("_")

        # Get the VIN number, using the index of the "vin" header.
        vin_number = values[vin_index]

        # Add the VIN number to the list.
        vin.append(vin_number)

# Print the list of VIN numbers.
print(vin)
Answered By: A.S

You can slice the strings around ‘_’, get the first part (at index 0) and append it to a list variable:

vin = []

with open('car.txt', 'r') as file:
    lines = file.readlines()    
for line in lines.splitlines():
    line = line.strip()
    if line:
        vin.append(line.split('_')[0])
        
vin.pop(0) # this one because I was too cheap to skip the header line :)
Answered By: Swifty

There are several ways to do this. The best depends on what you plan to do next. This file will parse with the csv module and you can use csv.reader to iterate all of the lines. To get vin specifically, you could

import csv

with open('car.txt', 'r') as file:
    next(file) # drop header
    vin = [row[0] for row in csv.reader(file, delimiter="_")]
Answered By: tdelaney

I would use regex to accomplish that. Assuming the file (car.txt) looks like this:

vin_brand_type_year_price
2132_BMW_330xi_2016_67000
1234_audi_a4_2019_92000
9876_mclaren_720s_2022_327000

I would use this python script:

import re

with open('car.txt') as f:
    data = f.readlines()

vin = []
for v in data:
    if match := re.match(r'(d+)', v.strip()):
        vin.append(match.group(0))

print(vin)

the

r’^(d)+’

is a regex for selecting the part of the text that starts with digits. This is to ensure any line in the file that doesn’t start with digits will be ignored.

Answered By: Mattias B

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=next(f).rstrip().split('_')
    data={}
    for row in f:
        for k, v in zip(header, row.rstrip().split('_')):
            data.setdefault(k, []).append(v)

Or, you can use some * magic and more succinctly do:

with open(your_file) as f:
    data={k:v for k,*v in (zip(*[e.rstrip().split("_") for e in f]))}

Either results:

>>> data
{'vin': ['2132', '1234', '9876'], 'brand': ['BMW', 'audi', 'mclaren'], 'type': ['330xi', 'a4', '720s'], 'year': ['2016', '2019', '2022'], 'price': ['67000', '92000', '327000']}
Answered By: dawg
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.