【问题标题】:save output values in txt file in columns python将输出值保存在 txt 文件中的 Python 列中
【发布时间】:2014-11-16 00:42:31
【问题描述】:

我的输入值给出对应的输出值为;

my_list = []
for i in range(1,10):
     system = i,i+2*i
     my_list.append(system)
     print(my_list)

[(1, 3)]

[(1, 3), (2, 6)]

[(1, 3), (2, 6), (3, 9)]

[(1, 3), (2, 6), (3, 9), (4, 12)]

我希望输出存储在 2 列中;其中1,2,3 是第一列元素,3,6,9 是第二列。

(1 3)
(2 6)
(3 9)

等等...然后将这些值写入文本文件中。对于文本文件,是否可以生成文本文件作为脚本的一部分?谢谢

【问题讨论】:

    标签: python python-2.7 python-3.x ipython


    【解决方案1】:
    file = open('out.txt', 'w')
    print >> file, 'Filename:', filename  # or file.write('...\n')
    file.close()
    

    基本上,查看“/n”并将其添加到变量中,它也应该附加到下一行:

    使用(“a”而不是“w”)继续附加到文件。该文件将位于您正在构建的目录中。

    【讨论】:

    • with 'system\n' 在第二列给我 1 2 3 4 和 system system system。
    • 尝试在变量和“/n”之间添加一个“+”号,这样:(variable+ '\n')
    【解决方案2】:

    您需要保存与i-1 具有相同索引的my_list 元素(您的范围从1 开始):

    my_list=[] 
    with open ('new.txt','w') as f:
     for i in range(1,10):
         system = i,i+2*i
         my_list.append(system)
         print(my_list)
         f.write(str(my_list[i-1])+'\n')
    

    输出:

    (1, 3)
    (2, 6)
    (3, 9)
    (4, 12)
    (5, 15)
    (6, 18)
    (7, 21)
    (8, 24)
    (9, 27)
    

    也如 cmets 中所说,您不需要 my_list 您可以使用以下代码:

    with open ('new.txt','w') as f:
     for i in range(1,10):
         system = i,i+2*i
         f.write(str(system)+'\n')
    

    【讨论】:

    • 谢谢。这只会将 out_put 文件中的一个值保存为 [(9, 27)]。
    • 感谢它有效!我正在编辑自己的脚本。谢谢
    • 欢迎,所以如果你确定你的答案,你可以告诉社区[接受答案][1] [1][meta.stackexchange.com/questions/5234/…
    • @Kasra:为什么不用f.write(str(system) + '\n') 而不是f.write(str(my_list[i-1])+'\n')
    猜你喜欢
    • 2021-06-28
    • 1970-01-01
    • 2023-02-01
    • 1970-01-01
    • 1970-01-01
    • 2014-12-29
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多