[英]How do I write a list of strings to a file in Python?
這是我的代碼:
from random import random
f = open('Attractors1.txt', 'w')
for i in range(10):
theta = (3.14/2)*random()
f.write(str(theta))
我正在嘗試創建一個包含10個theta值的列表,以便我可以在另一個程序中調用它們,但我認為這些對象沒有正確寫入。 我怎么知道我是否寫作? 每當我運行代碼並執行f.read()時,我都會收到錯誤消息,說文件未打開。
您無法read
以只寫模式打開的文件。 :)
由於你不是在循環中寫,你實際上只會吐出一個數字。 即使你修復了這個問題,你也會在一行中得到一堆數字,因為你沒有添加換行符。 .write
不像print
。
此外,它是一個好主意,使用with
當你認為它應該是在處理文件時,以確保文件被關閉。
試試這個:
import math
from random import random
with open('Attractors1.txt', 'w') as f:
for i in range(10):
theta = (math.PI / 2) * random()
f.write("{0}\n".format(theta))
f = open('Attractors1.txt', 'w')
for i in range(10):
theta = (3.14/2)*random()
f.write(str(theta))
f.close()
然后閱讀:
f = open('Attractors1.txt','r')
text = f.read()
print text
編輯:wups打敗了它
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.