2017-05-07 119 views
-1

我試圖寫這樣的文件:Python - 不寫入文件?

debugfile = open("file.txt", "w") 
debugfile.write("%i" % (feature['properties']['cellId'])) 
debugfile.close() 

這裏feature['properties']['cellId']是一個整數。該文件已創建,但保持空白。我錯過了什麼?

UPDATE 我試着寫入控制檯。

debugfile = open("file.txt", "w") 
print(feature['properties']['cellId']) 
debugfile.write("%i" % (feature['properties']['cellId'])) 
debugfile.close() 

這顯示控制檯: enter image description here 該文件仍然是空的。

+0

我不知道'功能'是如此不能測試,但'debugfile.write(「%i」%42)'工作正常。所以別的是錯的。是否有錯誤?你能否將你的例子更新爲失敗的事情,但我們可以運行?也許添加'print('feature ['properties'] ['cellId'])'然後張貼? – tdelaney

+0

大聲笑 - 你做到了!儘快。 – tdelaney

+0

嘗試使用字符串格式打印 – handle

回答

-2

你不想寫一個tuple?通過打印feature['properties']['cellId']

#!python 
#coding=utf-8 

import sys 
print(sys.version) 

debugfile = open("file1.txt", "w") 
debugfile.write("%i" % (123)) 
debugfile.close() 

debugfile = open("file2.txt", "w") 
debugfile.write("%i" % 123) 
debugfile.close() 
+0

這對於舊式格式很正常。如果格式字符串只有'1替換,您可以傳入一個對象或一個元素元組。如果有更多的替換,你傳入一個元組。 – tdelaney

+0

右:[字符串格式化操作](https://docs.python.org/2/library/stdtypes.html#string-formatting-operations),第二段。 – handle

1

檢查值:


沒關係,這仍然可以正常工作。

如果我初始化feature

feature = {'properties':{'cellId':1}} 

代碼工作。所以代碼沒有問題。

debugfile = open("file.txt", "w") 
debugfile.write("%i" % (feature['properties']['cellId'])) 
debugfile.close() 
+0

更新了問題。出現在控制檯上,不在文件中。 –

+0

它看起來像你正在寫一個循環,並按照@tdelaney的建議覆蓋值。如果您使用更多上下文(即循環)共享代碼,則可能會得到更好的答案。 – Nik