我在文件中有一组单词。我想添加一个由制表符分隔的新字符到所有这些单词并写入新文件。 我写的代码是
#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")
问题是新单词“X”与现有单词不对齐。我得到的样本输出是
A.
O
Mahesh
O
Anand
O
Anton
O
Plot
我想要的输出是:
Original File
word
word2
New File
word X
word2 X
我希望它能正确对齐
答案 0 :(得分:1)
readlines()
包含行尾字符:
In [6]: ff.readlines()
Out[6]: ['word1\n', 'word2']
您需要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))
答案 1 :(得分:0)
使用str.rstrip()
删除行尾\n
。
使用context manager
with
语句打开文件,
并使用str.formate
写入文件。
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'
答案 2 :(得分:0)
你应该删除' \ 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)