【问题标题】:How to write rows into txt file python如何将行写入txt文件python
【发布时间】:2021-12-09 18:02:25
【问题描述】:

我有代码将文件写入 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)

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

【问题讨论】:

    标签: python-2.7 file rows


    【解决方案1】:

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

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

    【讨论】:

      猜你喜欢
      • 2020-12-07
      • 1970-01-01
      • 1970-01-01
      • 2016-03-02
      • 1970-01-01
      • 2014-03-24
      • 1970-01-01
      • 1970-01-01
      • 2011-11-30
      相关资源
      最近更新 更多