Avinash Kumar Avinash Kumar - 29 days ago 9
Python Question

Read text from file and rearrange the columns?

I have a text file which has content:

A;B;C;D
a;b;c;d


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

B;C;D;A
b;c;d;a


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

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)]
        list_variable.append(line) 
Comments