我有一个这种格式的文本文件:
Item1 20 0
Item2 10 1
Item3 5 0
Item4 15 1
Item5 25 1
Item6 30 0
我如何.readlines()
只能附加" Item1"和" Item2"等。到列表,并留下数字和空格?
答案 0 :(得分:1)
您可以尝试下面的内容,
l = []
with open('/path/to/the/file') as file:
for line in file:
l.append(line.split()[0])
print(l)
通过list_comprehension。
print([line.split()[0] for line in open('/path/file')])
答案 1 :(得分:0)
lines = []
with open("text.txt", 'r') as fin:
lines = fin.readlines()
for line in lines:
print line.split(" ")[0]
答案 2 :(得分:0)
使用列表理解:
with open('sometext.txt', 'r') as f:
list1 = f.readlines()
print([ part.split(" ")[0] for part in list1 ])