簡體   English   中英

從文件讀取行但存儲為列表(python)

[英]read line from file but store as list (python)

我想讀取文本文件中的特定行並將元素存儲在列表中。

我的文本文件看起來像這樣

'item1' 'item2' 'item3'

我總是以每個字母作為元素的列表結束

我嘗試了什么

line = file.readline()
        for u in line:
            #do something
line = file.readline()
for u in line.split():
    # do stuff

這假設項目按空格分割。

用空格分割線,然后將它們添加到列表中:

# 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)

你所擁有的將讀取整行,然后循環遍歷該行中的每個字符。 您可能想要做的是將該行拆分為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           

您可以通過將各種函數串在一起來減少行數(和變量),但為了便於理解,我將它們分開。

你可以試試:

for u in line.split():

假設每個項目之間有空格。 否則,您將簡單地遍歷str ,從而按字符迭代。

您可能還想做:

u = u.strip('\'')

擺脫'

我會使用withre並且基本上在撇號之間取任何東西......(這對於在其中有空格的字符串起作用(例如:第item 1 item 2 ,但顯然嵌套或字符串轉義序列不會被捕獲)。

import re

with open('somefile') as fin:
    print re.findall("'(.*?)'", next(fin))
    # ['item1', 'item2', 'item3']

如果你想要列表中所有行的字符,你可以試試這個。

這使用雙列表理解。

with open('stackoverflow.txt', 'r') as file:
    charlist = [c for word in file.readline().split(' ') for c in word ]
    print(charlist)

如果你想擺脫一些char,你可以應用一些過濾器,例如; 我不想在我的列表中使用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)

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM