Append each line of a text as a element of a nested list

Question:

I’ve got a txt file that I want to read and append to a list.

source_file

This is what I have so far of my code:

for line in open(filename):
  items = line.rstrip('rn').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?

Asked By: André Portugal

||

Answers:

Solution

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)).

Final code

F = []
for line in open(filename):
  items = line.rstrip('rn').split('t')
  items = [item.strip() for item in items]
  F.append(tuple(items))  # Add tuple() here
print(F)

Output

[('4', '3050'), ('1', '4000')]

Answered By: Raida

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.

Answered By: Minura Punchihewa
Categories: questions Tags:
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.