0

I have a fixed-width txt input.txt that looks like

12345 1 23
23 12 2 11

And I have a separate file fixed-width.txt explaining how each column is separated.

1 2
2 3
3 2
4 3

The first column has 2 letters, the 2nd one 3 letters and so on. So I will need to convert input.txt into

12\t345\t 1\t 23\t\n
23\t 12\t 2\t 11\t\n

I tried to import fixed-width directly to MatLab or Python Pandas but failed. So I am here to ask how to convert this to tab-delimited txt.

user3123767
  • 1,115
  • 3
  • 13
  • 22
  • @Cyrbil I started learning python data manipulation from pandas, not from any simple python. Honestly I don't know very well about it. – user3123767 Nov 26 '15 at 17:30

1 Answers1

2
import pandas as pd
fmt = pd.read_csv('fixed-width.txt', delimiter=' ', 
                  header=None, names=['field', 'width'])
df = pd.read_fwf('input.txt', widths=fmt['width'], header=None)

To output as tab-delimited, you can just do

df.to_csv('output.txt', sep='\t')
Greg Whittier
  • 3,105
  • 1
  • 19
  • 14