简体   繁体   English

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

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

i want to read a specific line in a textfile and store the elements in a list. 我想读取文本文件中的特定行并将元素存储在列表中。

My textfile looks like this 我的文本文件看起来像这样

'item1' 'item2' 'item3'

I always end up with a list with every letter as an element 我总是以每个字母作为元素的列表结束

what I tried 我尝试了什么

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

This assumes the items are split by whitespace. 这假设项目按空格分割。

split the line by spaces and then add them to the list: 用空格分割线,然后将它们添加到列表中:

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

What you have there will read one whole line in, and then loop through each character that was in that line. 你所拥有的将读取整行,然后循环遍历该行中的每个字符。 What you probably want to do is split that line into your 3 items. 您可能想要做的是将该行拆分为3个项目。 Provided they are separated by a space, you could do this: 如果它们被空格隔开,您可以这样做:

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           

You can reduce the number of lines (and variables) here by stringing the various functions used together, but I left them separate for ease of understanding. 您可以通过将各种函数串在一起来减少行数(和变量),但为了便于理解,我将它们分开。

You can try: 你可以试试:

for u in line.split():

Which assumes there are whitespaces between each item. 假设每个项目之间有空格。 Otherwise you'll simply iterate over a str and thus iterate character by character. 否则,您将简单地遍历str ,从而按字符迭代。

You might also want to do: 您可能还想做:

u = u.strip('\'')

to get rid of the ' 摆脱'

I'd use with , re and basically take anything between apostrophes... (this'll work for strings that have spaces inside them (eg: item 1 item 2 , but obviously nested or string escape sequences won't be caught). 我会使用withre并且基本上在撇号之间取任何东西......(这对于在其中有空格的字符串起作用(例如:第item 1 item 2 ,但显然嵌套或字符串转义序列不会被捕获)。

import re

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

If you want all the characters of the line in a list you could try this. 如果你想要列表中所有行的字符,你可以试试这个。

This use double list comprehension. 这使用双列表理解。

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

If you want to get rid off some char, you can apply some filter for example; 如果你想摆脱一些char,你可以应用一些过滤器,例如; I don't want the char = ' in my list. 我不想在我的列表中使用char ='。

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

If this double list comprehension looks strange is the same of this. 如果这个双列表理解看起来很奇怪也是如此。

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