Rio
Rio

Reputation: 783

Parsing tab or space/s delimited file using Python

I have a file where each word is separated by either single space or tab or multiple spaces:

e.g.

address1.txt:

Bob lives in Boston
Sam lives    in Houston
Jay       lives in Ruston
Bill        lives in           Atlanta

I want to save the file as address2.txt where each word is tab separated.

How can i do it using Python?

Any help?

Thanks Rio

Upvotes: 1

Views: 7963

Answers (3)

Mark Reed
Mark Reed

Reputation: 95242

Use split to split on whitespace, then join to put the words back together with tabs.

with open('address1.txt') as fin, open('address2.txt','w') as fout:
  for line in fin:
    fout.write( "\t".join(line.split()) + "\n" )

Upvotes: 4

James Sapam
James Sapam

Reputation: 16930

Another way:

#!/usr/bin/python

with open('address1.txt', 'r') as ro, \
    open('address2.txt', 'a') as rw:
      for line in ro.readlines():
          ls = line.strip().split()
          rw.write('\t'.join(ls) + '\n')

Upvotes: 0

Steve Jessop
Steve Jessop

Reputation: 279195

Do '\t'.join(line.split()) on each line of the file. This works because split() with no arguments breaks up the line on any sequence of whitespaces.

Upvotes: 1

Related Questions