Python将文本文件中的每一行存储到列表中

2024-09-29 05:31:53 发布

您现在位置:Python中文网/ 问答频道 /正文

我有一个这样的文本文件,我想用python处理它

信息.txt

    firstname1
    surname1
    email@email.com1
    student1
 -------------------
    firstname2
    surname2
    email@email.com2
    student2
-----------------

我想写一个python代码,它在每个索引中检索和存储每一行,例如:[firstname,surname,email@email.com,student],而忽略{}

python代码

^{pr2}$

但我相信这是错误的,我对python很陌生,有人能给我指出正确的方向吗 我希望输出是这样的

输出

index 1 :first name: firstname1
         Surname: surname1
         Email: email@email.com1
         Student student1

index 2 :first name: firstname2
         Surname: surname2
         Email: email@email.com2
         student: student2

Tags: 代码nameindexemailsurnamestudentfirstcom1
2条回答

我知道最好用这种形式来解释如何做这样的事情的一般准则,但是对于这样一个简单的任务,代码本身就说明了问题,真的。。。在

我会这样做的。在

from pprint import pprint  # For nicer formatting of the output.

# For the sake of a self-contained example,
# the data is inlined here.
#
# `f` could be replaced with `open('log.txt').

f = """
    firstname1
    surname1
    email@email.com1
    student1
         -
    firstname2
    surname2
    email@email.com2
    student2
        -
""".splitlines()

data = []
current = None
for line in f:
    line = line.strip()  # Remove leading and trailing spaces
    if not line:  # Ignore empty lines
        continue  # Skip the rest of this iteration.
    if line.startswith('  -'):  # New record.
        current = None  # Clear the `current` variable
        continue  # Skip the rest of the iteration
    if current is None:  # No current entry?
        # This can happen either after a   - line, or
        # when we're dealing with the very first line of the file.

        current = []  # Create an empty list,
        data.append(current)  # and push it to the list of data.
    current.append(line)

pprint(data)

输出是列表列表:

^{pr2}$

这里有一个更优雅的解决方案。(只要您的文件严格遵守示例中的格式,即四行数据后面跟着一条虚线。)

from itertools import izip # skip this line if you are using Python 3

with open('info.txt') as f:
    result = [{'first name': first.strip(), 'Surname': sur.strip(),
               'Email': mail.strip(), 'student': stud.strip()}
              for first, sur, mail, stud, _ in izip(*[f]*5)]

这将为您提供如下词典列表:

^{pr2}$

其中“index 1”对应于列表的第一个元素(即result[0]),“index 2”对应于列表的第二个元素,依此类推。在

例如,您可以通过以下方式获得index == 2的姓氏:

index = 2
result[index - 1]['Surname']

如果你真的为索引的移位而烦恼,你可以根据结果建立一个字典。演示:

>>> result = dict(enumerate(result, 1))
>>> result
{1: {'first name': 'firstname1', 'Surname': 'surname1', 'Email': 'email@email.com1', 'student': 'student1'}, 2: {'first name': 'firstname2', 'Surname': 'surname2', 'Email': 'email@email.com2', 'student': 'student2'}}
>>>
>>> result[2]['Surname']
'surname2'
>>>
>>> for index, info in result.items():
...     print index, info['first name'], info['Surname'], info['Email'], info['student']
... 
1 firstname1 surname1 email@email.com1 student1
2 firstname2 surname2 email@email.com2 student2

相关问题 更多 >