我想要实现的是尝试打开带有文本的文本文件。文本格式如下:
Bear
Car
Plant
等。现在我现在的代码:
try:
with open(info) as information:
for line in information.readlines():
line = line.split()
except IOError as error:
print("Failed to open. Try again.")
仅打印出列表中的最后一行。我想要做的是打印出列表中的所有单词。
因此,对于上面的示例,当我打印(行)时,它会打印['Plant']
,但我想要['Bear','Car','Plant']
。
有人能引导我朝正确的方向走吗?
答案 0 :(得分:2)
您不需要拆分,需要使用str.strip()
剥离(删除换行符),然后将结果添加到列表中:
lines = []
with open(info) as information:
for line in information:
lines.append(line.strip())
请注意,根本不需要file.readlines()
来电;只需迭代文件即可。
您可以通过阅读整个文件并使用str.splitlines()
:
with open(info) as information:
lines = information.read().splitlines()
或者你可以在列表理解中使用迭代:
with open(info) as information:
lines = [line.strip() for line in information]
答案 1 :(得分:0)
readlines
将文件作为列表
try:
with open(info) as information:
lines = information.readlines()
except IOError as error:
print("Failed to open. Try again.")
您也可以使用list
:
try:
with open(info) as information:
lines = list(information)
except IOError as error:
print("Failed to open. Try again.")