2017-03-29 39 views
0

因此,我想读取文本文件每行的每个字符(用空格分隔),并将它们添加到每个列表的单独索引中线。将每个文本文件行中的每个字符添加到Python中的列表中

file = open("theTextFile.txt", 'r+') 
pal = [] 

words = file.split(' ') 
pal.append(words) 

print(pal) 
split_line(file) 

该文本文件具有由每行的空格分隔的单个字符。 编辑器不允许从文本文件中输入标点符号,但下面是它的外观示例。

,R 0牛逼Ø[R

R Aç权证

+0

[这](http://stackoverflow.com/questions/3277503/how-do-i-read-a-file逐行列表?rq = 1)将会很有帮助。 –

+0

您能举一个简短的输入例子和期望的输出吗? – AndreyF

+0

这里有很多关于如何在Python中读取文件并将其输出到像[这里]列表的文章(http://stackoverflow.com/questions/28781476/turning-list-from-text-file- into-python-list),[here](http://stackoverflow.com/questions/35273534/python-read-lines-of-an-entire-file-and-efficiently-storing-the-ones-i-want在)或[这里](http://stackoverflow.com/questions/37002578/python-read-file-into-list-edit)你应该能够找出这一个。但是你的问题并不清楚,你需要举一个“theTextFile.txt”的例子,告诉我们你的预期输出是什么。 – dirkgroten

回答

0

这是我做过什么来解决我的问题:

lines = open('theTextFile.txt','r') 

secondList = [] 
for line in lines: 
    line = line.split() 
    secondList.append(line) 
0

也许你想这样吗?

words = [] 
with open('theTextFile.txt', 'r') as fp: 
    words = sum([l.strip().split(' ') for l in fp], []) 
print(words) 
相关问题