Click here to Skip to main content
15,846,144 members
Please Sign up or sign in to vote.
0.00/5 (No votes)
See more:
I would like to read the columns of a txt file in python. I have a txt file with 30 columns. I would like to set a variable for each column (I mean for example, a for column 1, b for column 2, c for column 3 etc.)
Coule you please help me? Witch command should I use?

What I have tried:

from difflib import SequenceMatcher

with open('input_text.txt ','r') as fin:'\n')
    for index in range(len(data)):
#     columns = line.split()

Updated 2-Mar-23 21:54pm
Richard MacCutchan 2-Mar-23 12:35pm    
Assuming that your columns are separated by spaces, and there are no spaces within those columns, then the above code should work. Just remove the comment character from line 6.
Member 14991075 2-Mar-23 12:38pm    
ok how to set a for column 1, and b for column 2?
Richard MacCutchan 2-Mar-23 13:25pm    
See below.

After the line
columns = line.split()

columns is a list with a number of elements (the number of separate items). So you can then do something like:
a = columns[1]
b = columns[2]
... etc.

Alternatively you could say
a, b, c, d, e, ...  = line.split()

But it would be better to just use the index values to refer to each item.
Share this answer
I'd suggest to use pandas. There's a method called pandas.read_csv — pandas 1.5.3 documentation[^].
This is very fast and flexible.

Imagine, you've got such of file:

There's no header and a comma is used as a column separator. Then:
import pandas as pd

filename = 'FullFileNameHere.txt' 
df = pd.read_csv(filename, delimiter=',',usecols=[0,2],header=None)
#to get first column data, use:
a = df[0]
#to get 5. element on the list, use:

That's all! Try it!
Share this answer
import pandas as pd

filename = 'input_text.txt' 
df = pd.read_csv(filename, sep='\t',usecols=[0,1], header=None, index_col=False)

a = df[0]
b = df[1]
Share this answer
Maciej Los 3-Mar-23 10:38am    
This is not an answer. Please, delete it.
BTW: see updated answer.

This content, along with any associated source code and files, is licensed under The Code Project Open License (CPOL)

CodeProject, 20 Bay Street, 11th Floor Toronto, Ontario, Canada M5J 2N8 +1 (416) 849-8900