X
X
Xacker_Name2021-09-10 19:04:30
Python
Xacker_Name, 2021-09-10 19:04:30

Hai, how do I split a line from a split file; on variables in python?

Hai, how do I split a line from a split file ; on variables in python?

Let's say there is a file test.txt
Contents of the file:
test1; test2
How can I split the string into variables through python? Let's say:
1 = test1
2 = test2

Answer the question

In order to leave comments, you need to log in

2 answer(s)
A
antares4045, 2021-09-10
@rt2233

depends on very many factors:
if you know the number of variables in advance, then it is enough

with open('test.txt', 'r') as file:
    v1, v2 = file.readline().split(';')
print(v1, v2)

Otherwise, it's more fun.
with open('test.txt', 'r') as file:
    lineindex = 0
    for line in file:
        values = line.split(';')
        for colindex in range(len(values)):
            globals()[f'v_{lineindex}_{colindex}'] = values[colindex]
        lineindex += 1

print(v_0_0, v_0_1)

but perhaps you don’t need to hit global variables, if it’s enough just to add it to the list, then
with open('test.txt', 'r') as file:
    acc = []
    for line in file:
        acc.append(line.split(';'))

print(acc)

M
Maxim Siomin, 2021-09-10
@MaxSiominDev

with open('file.txt', 'r') as file:
    content = str(file.readlines()).split(';')

Didn't find what you were looking for?

Ask your question

Ask a Question

731 491 924 answers to any question