Python将文件拆分为列表 [英] Python split file into list
本文介绍了Python将文件拆分为列表的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!
问题描述
我无法使用以下功能.似乎可以很好地分割文件,但仅将其作为一个元素返回
I'm having trouble with the function below. It seems to split the file fine but then only returns it as one element
功能:
def splitRoute():
route = []
for line in open("route.txt","r").readlines():
line = line.replace("\r","")
line = line.replace("\n","")
line = string.split(line, '>')
route.append(line)
return route
输出:
[['B', 'F']]
route.txt内容:
route.txt contents:
B>F
是否仅由于文件中只有一行而返回一个元素? 我还有另一个功能,可以将另一个文件拆分为7x7列表,该列表可以正常工作,但是因为它有7行,所以只能覆盖所有七个元素吗?
Is it only returning one element because there is only one line in the file? I have another function that splits another file into a 7x7 list that works fine but is that only reaching all seven elements across because it has 7 lines?
推荐答案
为什么要替换换行符?只需拆分字符串:
Why are you replacing newlines? Just split the string:
def splitRoute():
route = []
for line in open('route.txt', 'r'):
route.append(line.strip().split('>'))
return route
这篇关于Python将文件拆分为列表的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!
查看全文