【问题标题】:Array output from a while loop to a text file using python使用python从while循环到文本文件的数组输出
【发布时间】:2019-10-24 12:18:50
【问题描述】:

我正在生成一个温度 (T) 数组和另一个位置 (X) 数组,我可以使用简单的命令 plt.plot(X, T) 绘制它。但是,我正在努力将此数据输出到文本文件。 请问,有人可以在这方面帮助我吗?谢谢你。 len(T) 打印 12,len(X) 也打印 12。 这就是我在 Python 中尝试的方式: 这些是while循环后的命令,因此数据已经生成。 我想同时写 T[i] 和 X[i]

with open('Temp.txt', 'w') as fh: # this is where I like to write my Temperature data
    for i in range (12): # trying to loop around all the points, up to 12
        fh.write(T[i]) # trying to write temperature to the file, and if it works, need to write the same for the position, X. 

【问题讨论】:

  • 也许this可以帮你把数组的所有成员写入文件
  • 感谢您的留言,但这并没有真正帮助。

标签: arrays file text


【解决方案1】:

好吧,也许你应该试试这个: 当然,我认为您希望将两个值都放在同一个文件中,例如 "T[i] : X[i]"

T=(1,2,3,4,5)
X=(6,7,8,9,10)
outfile = open('outfile.txt', 'w') #open a file in same directory as the code to write
for a,b in zip(T,X):    # iterate over the list items
   outfile.write(str(a) +" : "+str(b)+ '\n') # write to the file
outfile.close() 

如果你希望每个文件都放在单独的文件中,那么你应该这样做:

outfile1 = open('outfile1.txt', 'w') 
for a in T:
   outfile1.write(str(a) '\n') 
outfile1.close()
outfile2 = open('outfile2.txt', 'w') 
for a in X:
   outfile2.write(str(a) '\n') 
outfile2.close() 

【讨论】:

  • 太棒了,它现在就像一个魅力。您给出的示例是针对元组的,我拥有的数据是列表。只需将括号更改为方括号,一切都对我有用。我从来没有遇到过 zip(),将阅读更多关于它的内容。我才刚学 Python 几个月,感谢分享知识和解决问题。
猜你喜欢
  • 1970-01-01
  • 2017-06-18
  • 2022-01-23
  • 1970-01-01
  • 2020-10-25
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多