我試圖複製具有許多單詞並將內容移動到另一個文件的文件的內容。原文件有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
我明白我的問題是在底部,而試圖導入到新的文件,也許一個簡單的解釋可能會得到我在那裏,非常感謝。
究竟發生了什麼,它與預期的行爲有什麼不同?發佈你得到的確切的錯誤,如果有的話。 – stybl
'x'即使您已將其指定爲'int',它也會更改爲for循環中的字符串。 –
我得到的錯誤是: 如果len(words [x])> = 5: TypeError:列表索引必須是整數或切片,而不是str –