我试图复制具有许多单词并将内容移动到另一个文件的文件的内容。原文件有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 –