我正在尝试复制具有多个单词并将内容移动到另一个文件中的文件的内容。原始文件有3个字母的单词,我想整理出来。不幸的是,我没有成功实现它。我是Python的新手,有一些Java经验所以我试着做这个非常基本的。代码如下:
# 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 :(得分: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
中第一个元素的值,然后是第二个元素的值,依此类推每次迭代。然而,您试图将其视为正常for循环,通过索引遍历列表。当然这没有用。
有两种方法可以修复代码。您可以采用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()
循环遍历列表索引的范围。这将产生类似于传统for循环的行为:
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循环的开头重新分配。