Reputation: 15
I've got a txt file that I want to read and append to a list.
This is what I have so far of my code:
for line in open(filename):
items = line.rstrip('\r\n').split('\t') # strip new-line characters and split on column delimiter
items = [item.strip() for item in items] # strip extra whitespace off data items
F.append(items)
So far so good. The issue here is that I want each line to be appended to a list with the following structure:
F = [(4,3050),(1,4000),]
How do I make it read the file to append to that specific structure?
Upvotes: 0
Views: 57
Reputation: 2025
You can also achieve this using pandas,
import pandas as pd
df = pd.read_csv('csp_test.txt', sep=" ", header = None)
list(df.itertuples(index=False, name=None))
If you want a one liner,
import pandas as pd
list(pd.read_csv('csp_test.txt', sep=" ", header = None).itertuples(index=False, name=None))
Either way, you will get the following output,
[(4, 3050), (1, 4000)]
This way, you don't have to worry about splitting your fields or performing any strip operations.
Upvotes: 0
Reputation: 1506
Firstly, be sure you are using tabulations in your text file. According to your screenshot, it seems that your are using a space.
Secondly, to store a tuple rather than a list in your list F
use F.append(tuple(items))
.
F = []
for line in open(filename):
items = line.rstrip('\r\n').split('\t')
items = [item.strip() for item in items]
F.append(tuple(items)) # Add tuple() here
print(F)
[('4', '3050'), ('1', '4000')]
Upvotes: 1