如何将行写入txt文件python

时间:2016-09-09 16:30:41

标签: python-2.7 file rows

我有代码将文件写入writer,然后使用writer写入csv。 这都是使用'import csv'库。 但问题是,我有像123456789.123456789这样的数字,当它写入csv时,数字被截断为123456789.1234。所以我想把结果写成txt,但不知道如何将行写入txt。

  if results.get('rows', []):
   for row in results.get('rows'):
     for i in range(len(row)):
       old, new = row[i], str()
       for s in old:
        new += s if s in string.printable else ''
       row[i]=new
     writer.writerow(row)



path = '/Users/sailormoon/Desktop/' 
filename = 'sailormoon.csv' 
with open(path + filename, 'wt') as f:
 writer = csv.writer(f, lineterminator='\n')

我认为是伪代码:

path = '/Users/sailormoon/Desktop/' 
filename = 'sailormoon.txt' 
with open(path + filename, 'wt') as f:
 f.write(row)

我可以用什么库将行写入txt for python?谢谢!

1 个答案:

答案 0 :(得分:0)

将所有数字作为字符串附加到列表中。然后使用for循环:

numbers = ['123456789.123456789', '123453459.128967678']

with open(path + '\\numbers.txt', 'w') as out:
    for n in numbers:
        out.write(n + '\n')