'Read and save data from file txt in a list with python code
This is my file.txt:
1, AC233FA28A31, -64, 1.0741886104850389
1, AC233FA28A32, -67, 4.990341223352587e+16
2, AC233FA28A31, -66, 1.240560004316543
2, AC233FA28A32, -61, 4190057960.7655835
3, AC233FA28A31, -64, 1.0741886104850389
3, AC233FA28A32, -65, 685898450406726.6
How can I read the third column and save the data in a List?
The output of Python code must be this list=[-64, -67, -66, -61, -64....]
Solution 1:[1]
You can do that easily with Pandas:
import pandas as pd
df = pd.read_csv('file.txt', sep='\s+', header=None)
res = df[2].tolist()
print(res)
And you will have your list saved in res.
Solution 2:[2]
Something like this:
with open('file.txt', 'r+') as file:
# split in lines
for line in file.read().split('\n'):
# Parse the single lines
riga = line.split(',')
riga[0] = int(riga[0])
riga[1] = riga[1].strip()
riga[2] = int(riga[2])
riga[3] = int(riga[3])
lista.append(riga)
Otherwise, if you want to handle it as a dataframe, you should use pandas Python's library, as @Flavio suggested.
Solution 3:[3]
You can do this using csv.
import csv
col1 = []
col2 = []
col3 = []
with open('file.txt') as f:
for row in csv.reader(f):
col1.append(row[0])
col2.append(row[1])
col3.append(float(row[2]))
print(col3)
Solution 4:[4]
If you dont want to use the Pandas library you can use csv:
with open("myfile.txt") as file:
data= csv.reader(file)
my_list = []
for row in data:
my_list.append(int(row[2].strip()))
Solution 5:[5]
You can use pandas and read_csv. Importantly, you should use header=None since no column names are available in the file.txt
import pandas as pd
df = pd.read_csv('file.txt', header=None)
# if you really want a list
out = list(df[2].values)
Sources
This article follows the attribution requirements of Stack Overflow and is licensed under CC BY-SA 3.0.
Source: Stack Overflow
| Solution | Source |
|---|---|
| Solution 1 | Flavio |
| Solution 2 | FLAK-ZOSO |
| Solution 3 | Muhammad Mohsin Khan |
| Solution 4 | Bendik Knapstad |
| Solution 5 | Luca Clissa |
