我想读取文本文件中的特定行并将元素存储在列表中。从文件读取行但作为列表存储(Python)
我的文本文件看起来像这样
'item1' 'item2' 'item3'
我总是一个清单,每一个字母结束了作为一个元素
我试过
line = file.readline()
for u in line:
#do something
我想读取文本文件中的特定行并将元素存储在列表中。从文件读取行但作为列表存储(Python)
我的文本文件看起来像这样
'item1' 'item2' 'item3'
我总是一个清单,每一个字母结束了作为一个元素
我试过
line = file.readline()
for u in line:
#do something
你可以试试:
for u in line.split():
它假设有各项目之间的空格。否则,您只需遍历str
,从而逐个字符地迭代。
您也可能想要做的:
u = u.strip('\'')
摆脱的'
line = file.readline()
for u in line.split():
# do stuff
这是假定项目被空白分割。
你在那里会看到一整行,然后遍历该行中的每个字符。你可能想要做的是将该行分割成3个项目。只要它们用空格隔开,你可以这样做:
line = file.readline() # Read the line in as before
singles = line.split(' ') # Split the line wherever there are spaces found. You can choose any character though
for item in singles: # Loop through all items, in your example there will be 3
#Do something
您可以串在一起使用的各种功能在这里降低线(和变量)的数目,但我把它们分开为便于理解。
我会用with
,re
基本上采取引号之间的任何东西......(这会为工作(例如:item 1
item 2
,但明显嵌套或字符串转义序列不会被捕获)。
import re
with open('somefile') as fin:
print re.findall("'(.*?)'", next(fin))
# ['item1', 'item2', 'item3']
分裂空格行,然后将它们添加到列表:
# line = ('item1' 'item2' 'item3') example of line
listed = []
line = file.readline()
for u in line.split(' '):
listed.append(u)
for e in listed:
print(e)
如果你希望所有在列表中的行,你可以试试这个角色。
这使用双列表理解。
with open('stackoverflow.txt', 'r') as file:
charlist = [c for word in file.readline().split(' ') for c in word ]
print(charlist)
如果你想摆脱一些字符,你可以申请一些过滤器,例如;我不想要char ='在我的列表中。
with open('stackoverflow.txt', 'r') as file:
charlist = [c for word in file.readline().split(' ') for c in word if(c != "'")]
print(charlist)
如果这个双列表的理解看起来很奇怪的话就是这个样子。
with open('stackoverflow.txt', 'r') as file:
charlist = []
line = file.readline()
for word in line.split(' '):
for c in word:
if(c != "'"):
charlist.append(c)
print(charlist)
你能显示导致你的错误/问题的代码片段吗? – BlackVegetable 2013-02-21 15:18:24
I 2nd BlackVegetable – Drewdin 2013-02-21 15:19:11
在line.split()中试试''你也可以''.strip()''''from'u' – dmg 2013-02-21 15:23:27