从一个文件中获取信息并在Python中打印到另一个文件
问题描述:
我试图复制具有许多单词并将内容移动到另一个文件的文件的内容。原文件有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
我明白我的问题是在底部,而试图导入到新的文件,也许一个简单的解释可能会得到我在那里,非常感谢。
答
的问题是在这里:
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是持有这些信息而不是一个整数使我失望。 –
究竟发生了什么,它与预期的行为有什么不同?发布你得到的确切的错误,如果有的话。 – stybl
'x'即使您已将其指定为'int',它也会更改为for循环中的字符串。 –
我得到的错误是: 如果len(words [x])> = 5: TypeError:列表索引必须是整数或切片,而不是str –