user3368375
user3368375

Reputation: 57

Writing tab spaced words to a file in Python

I have a set of words in a file. I want to add a new character separated by tab to all these words and write to a new file. The code I wrote is

#file to read is opened as ff and file to write is opened as fw.
count = "X"
x = ff.readlines()
for word in x:
     fw.write('%s\t%s'% (word, count))
     fw.write("\n")

The problem is the new word 'X' is not alignment with the existing words. The sample output i am getting is

 A.
      O
 Mahesh
      O
 Anand
      O
 Anton
      O
 Plot

The output I want is:

Original File
word
word2

New File 
word    X
word2    X

I want it to be aligned properly

Upvotes: 0

Views: 1206

Answers (3)

unutbu
unutbu

Reputation: 879371

readlines() includes the end of line characters:

In [6]: ff.readlines()
Out[6]: ['word1\n', 'word2']

You need to strip them off:

word = word.rstrip()

count = "X"
with open('data', 'r') as ff, open('/tmp/out', 'w') as fw:
    for word in ff:
        word = word.rstrip()  # strip only trailing whitespace
        fw.write("{}\t{}\n".format(word, count))

Upvotes: 1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

use str.rstrip() as to remove end of line \n.

use context manager with statement to open the file, and use str.formate to write in file.

with open('out_file.txt') as ff, open('in_file.txt', 'w+') as r:
    for line in ff:
        r.write('{}\t{!r}\n'.format(line.rstrip(), 'X'))
    r.seek(0)
    print r.read()

>>> 
   word1    'X'
   word2    'X'
   word3    'X'
   word4    'X'

Upvotes: 0

Hayes Pan
Hayes Pan

Reputation: 615

you should remove '\n':

count = "X"
with open('data', 'r') as ff, open('/tmp/out', 'w') as fw:
    for word in ff.readlines():
        print >> fw, '%s\t%s' % (word.rstrip(), count)

Upvotes: 0

Related Questions