我正在尝试复制包含许多单词的文件的内容并将内容移动到另一个文件中。原始文件有 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
我知道在尝试导入新文件时我的问题出在底部,也许简单的解释可以帮助我解决问题,非常感谢。
请您参考如下方法:
问题出在这里:
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 不是循环开始后的数字。它是一个字符串。
我认为您误解了 for 循环在 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 循环开始时被重新分配。
