Avinash Kumar Avinash Kumar - 1 year ago 61
Python Question

Read text from file and rearrange the columns?

I have a text file which has content:


I am reading the file in python and wants to rearrange the column such as-


I have tried reading column -

file = open('add.txt','r')
text = file.read()
column1 = x[0] for x in text

But this didn't help. So I need a way to convert it.

Answer Source

You can use the csv module to read your file into lists, then is just a matter of re-indexing the list order.

import csv
list_variable = []
with open("file.txt") as add_txt:
    reader = csv.reader(add_txt, delimiter =';')
    for line in reader:
        line += [line.pop(0)]
Recommended from our users: Dynamic Network Monitoring from WhatsUp Gold from IPSwitch. Free Download