我想讀取文本文件中的特定行並將元素存儲在列表中。從文件讀取行但作爲列表存儲(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