从文件中读取行,但存储为列表(python)

从文件中读取行,但存储为列表(python),python,Python,我想读取文本文件中的特定行,并将元素存储在列表中 我的文本文件看起来像这样 'item1' 'item2' 'item3' 我总是以每个字母作为元素的列表结束 我试过的 line = file.readline() for u in line: #do something 这假定项目按空格分割 您在那里看到的内容将在中读取一整行,然后循环遍历该行中的每个字符。您可能想做的是将该行拆分为3项。如果它们之间有空格,则可以执行以下操作: line = fil

我想读取文本文件中的特定行,并将元素存储在列表中

我的文本文件看起来像这样

'item1' 'item2' 'item3'
我总是以每个字母作为元素的列表结束

我试过的

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

这假定项目按空格分割

您在那里看到的内容将在中读取一整行,然后循环遍历该行中的每个字符。您可能想做的是将该行拆分为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('\'')

为了摆脱

,我将使用
re
,基本上在撇号之间取任何东西。。。(这将适用于内部有空格的字符串(例如:
项目1
项目2
,但显然不会捕获嵌套或字符串转义序列)


按空格拆分该行,然后将其添加到列表中:

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

您能否显示导致错误/问题的代码段?请在第行中为u尝试
。拆分():
此外,您可能需要从
u
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)