2017-11-18 77 views
2

我試圖複製具有許多單詞並將內容移動到另一個文件的文件的內容。原文件有3個字母的單詞,我想解決。不幸的是,我沒有成功實現它。我更新Python與一些Java的經驗,所以即時通訊試圖做到這一點很基本。代碼如下:從一個文件中獲取信息並在Python中打印到另一個文件

# Files that were going to open 
filename = 'words.txt' 
file_two = 'new_words.txt' 

# Variables were going to use in program 

# Program Lists to transfer long words 
words = [] 

# We open the file and store it into our list here 
with open(filename, 'r') as file_object: 
    for line in file_object: 
     words.append(line.rstrip("\n")) 

# We transfer the info into the new file 
with open(file_two, 'a') as file: 
    x = int(0) 
    for x in words: 
     if len(words[x]) >= 5: 
      print(words[x]) 
      file.write(words[x]) 
      x += 1 

我明白我的問題是在底部,而試圖導入到新的文件,也許一個簡單的解釋可能會得到我在那裏,非常感謝。

+0

究竟發生了什麼,它與預期的行爲有什麼不同?發佈你得到的確切的錯誤,如果有的話。 – stybl

+0

'x'即使您已將其指定爲'int',它也會更改爲for循環中的字符串。 –

+0

我得到的錯誤是: 如果len(words [x])> = 5: TypeError:列表索引必須是整數或切片,而不是str –

回答

1

的問題是在這裏:

with open(file_two, 'a') as file: 
    x = int(0) 
    for x in words: 
     if len(words[x]) >= 5: 
      print(words[x]) 
      file.write(words[x]) 
      x += 1 

原因你得到的錯誤是x不是一個數字,一旦循環開始。它是一個字符串。

我想你誤解了python中循環的工作原理。它們更類似於其他語言的foreach循環。當你做for x in words時,x被賦予words中第一個元素的值,然後是第二個元素,依次類推。然而,你正在試圖把它當作循環的正常對象,按索引遍歷列表。當然這不起作用。

有兩種方法可以解決您的代碼問題。您可以採取的foreach方法:

with open(file_two, 'w') as file: 
    for x in words: #x is a word 
     if len(x) >= 5: 
      print(x) 
      file.write(x) 

或者,通過列表的索引的範圍使用len()循環。這將產生類似於傳統的行爲循環:

with open(file_two, 'a') as file: 
    for x in range(len(words)): #x is a number 
     if len(words[x]) >= 5: 
      print(words[x]) 
      file.write(words[x]) 

也沒有必要手動增加x,或給x初始值,因爲它是在的開始for循環重新分配。

+1

很多感謝!在我發佈之前,我嘗試了幾個不同的東西。我採取了你提供的第一種方法,它工作。也感謝你對循環的解釋,因爲我習慣了Java,事實上x是持有這些信息而不是一個整數使我失望。 –

相關問題