Mani Sai Ratnala
Mani Sai Ratnala

Reputation: 7

Select columns from a text file and print it as a list

I have no experience in Python. For a project work, I need to use Python. The input file has contents as follows

1 ; 35 ; 3 ; 3 ; 22728
2 ; 34 ; 10 ; 1 ; 10773
3 ; 34 ; 10 ; 3 ; 4074
4 ; 55 ; 1 ; 2 ; 151335
5 ; 55 ; 1 ; 3 ; 268476
6 ; 83 ; 19 ; 1 ; 69939
7 ; 55 ; 1 ; 1 ; 9821
8 ; 55 ; 1 ; 0 ; 19124
9 ; 16 ; 0 ; 2 ; 1526077
10 ; 84 ; 13 ; 3 ; 14473383
11 ; 25 ; 35 ; 2 ; 18263375

The format is a number,space,semi-colon,space,number,space,semi-colon and so on. Now I need a program which extracts second and third number from each and everyline. I So in the need the output should be

35,3,34,10,34,10,55,1,55,1,83,19,55,1,55,1,16,0,84,13,25,35.

Please help me with this guys.

Upvotes: 0

Views: 394

Answers (3)

B200011011
B200011011

Reputation: 4258

This should work. input.txt should be on the same folder as python code.

Code:

output_list = []

## read data from input.txt file
with open("input.txt", "r") as f:
  lines = f.readlines()

  ## read line by line
  for line in lines:
    split_data = line.split(';')

    ## append the 2nd and 3rd column into a list 
    output_list.append("," + split_data[1].strip() + "," + split_data[2].strip())

  ## create string from list
  output_str = ("".join(output_list) + ".")[1:]
  print(output_str)

Output:

35,3,34,10,34,10,55,1,55,1,83,19,55,1,55,1,16,0,84,13,25,35.

Upvotes: 0

scotty3785
scotty3785

Reputation: 7006

Similar to Zaven's answer

from io import StringIO
import csv

text = """1 ; 35 ; 3 ; 3 ; 22728
2 ; 34 ; 10 ; 1 ; 10773
3 ; 34 ; 10 ; 3 ; 4074
4 ; 55 ; 1 ; 2 ; 151335
5 ; 55 ; 1 ; 3 ; 268476
6 ; 83 ; 19 ; 1 ; 69939
7 ; 55 ; 1 ; 1 ; 9821
8 ; 55 ; 1 ; 0 ; 19124
9 ; 16 ; 0 ; 2 ; 1526077
10 ; 84 ; 13 ; 3 ; 14473383
11 ; 25 ; 35 ; 2 ; 18263375"""

file = StringIO(text)
iCsv = csv.reader(file, delimiter=";")
itemList = []
for row in iCsv:
    itemList.append(row[1].strip())
    itemList.append(row[2].strip())

print(itemList)

This will contain a list that contains the 2nd and 3rd item from each row. The StringIO part can be swapped out with an open('file.txt') when reading from a file rather than a string.

Upvotes: 1

Raymond Reddington
Raymond Reddington

Reputation: 1837

Python has builtin csv library, it has custom delimiters:

import csv
    with open('file.txt', newline='\n') as csvfile:
        rd = csv.reader(csvfile, delimiter=' ; ')
        for row in rd:
            print(row)

Upvotes: 1

Related Questions