Click here to Skip to main content
15,886,026 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:
    data=fin.read().split('\n')
    for index in range(len(data)):
#     columns = line.split()
     print(data)
Python

Posted
Updated 2-Mar-23 20:54pm
v2
Comments
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
Python
columns = line.split()

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

Alternatively you could say
Python
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.

[EDIT]
Imagine, you've got such of file:
-3153.61743,-6115.18164,-3289.31226
-3256.75195,-6075.70801,-3550.83057
-3775.00977,-5870.36035,-3817.91870
-3890.03223,-5819.92871,-3797.58984
-4134.60156,-5724.16309,-3651.39648

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

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


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

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

#print(df)
a = df[0]
print(a)
b = df[1]
print(b)
 
Share this answer
 
Comments
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