2012-11-24 28 views
1

我有一個文本文件:Python讀物在一個文件中的每個字符串

1 0 1 0 1 0 

1 0 1 0 1 0 

1 0 1 0 1 0 

1 0 1 0 1 0 

我希望能夠檢索每個字符串,並將其轉換爲整數數據類型,但我在​​

一段代碼結果
tile_map = open('background_tiles.txt','r'); 

    for line in tile_map: 

     for string in line: 

      self.type = int(string); 

檢索數據並將其成功轉換的正確方法是什麼?

+1

相關:[將文件字符串讀入數組(以pythonic方式)](http://stackoverflow.com/a/11052673/4279) – jfs

回答

4

一件事時,通過文件迭代是換行字符包括,當你試圖施放,使用int(),您將收到您的錯誤正在引用(因爲Python不知道如何將其轉換爲整數)。嘗試使用類似:

with open('background_tiles.txt', 'r') as f: 
    contents = f.readlines() 

for line in contents: 
    for c in line.split(): 
     self.type = int(c) 

with是上下文管理器,它通常是處理文件,因爲它處理諸如關閉你時自動離開塊的東西更有效的方式。 readlines會將文件讀入列表中(每行代表列表元素),並且split()在空間上分裂。

2

您的行包含字符串 - "1 0 1 0 1 0"。您需要在空間分割你行 - 記

for string in line.split(): 
    self.type = int(string); 
+0

非常感謝。最後決定 – starhacker

+0

@ Unit978 ..不客氣:)你可以在10分鐘後接受答案。 –

相關問題