繁体   English   中英

使用 open() Python 和多个 for 循环

[英]with open() Python and multiple for loops

对于家庭作业,我被要求从 txt 文件中提取数据。 该文件包含几个不同人的姓名+出生日期。

文本文件:

Full name1, DOB 1
Full name2, DOB 2
etc...

output 应该是:

Names
Full Name 1
Full Name 2
etc..

DOB

Dob 1 
Dob 2
etc...

我设法做到了,但我不确定这是最好的方法。 能否请您确认一下是否正确? 我是 Python 的新手,所以我需要一个非常简单的代码。 例如没有功能。

with open('DOB.txt', 'r') as f:
    
    print('Name')
    for line in f:
        # rest of code

print()

with open('DOB.txt', 'r') as f:
     print('Date of birth')
     for line in f:
        # rest of code

两次打开文件是否正确?

这是一种快速简便的方法。 不需要打开文件两次,但这样做并没有错。

def display_info():
    names, dobs = [], []
    with open('DOB.txt', 'r') as f:
        lines = f.read().splitlines()
        for line in lines:
            # Split each line into respective name and dob
            name, dob = line.split(", ")
            # Append to our lists to print out later
            names.append(name)
            dobs.append(dob)
    # Print names first, then dobs
    print("Names")
    for name in names:
        print(name)
    # Line break
    print("")
    print("Date of births")
    for dob in dobs:
        print(dob)

显示信息()

您可以像这样逐行读取文件:

data = {}

with open(filename) as file:
    for line in file:
        name, age = line.rstrip().split(',')
        data[name] = age

并打印你想要的数据:

print(data.keys()) #prints the names
print(data.values()) #prints the age

更简单的方法是通过列表读取行和使用逗号 uisng ittertools 分隔。

from itertools import chain
with open("Markus Pe.txt") as file:
    lines = [line.rstrip() for line in file]

lines = list(chain.from_iterable(ele.split(",") for ele in lines))

dob =lines[1::2]
names = lines[::2]

print('names')
for x in names:
    print(x)

print('dob')
for x in dob:
    print(x)

样品 output #

names
Full name1
Full name2

dob 
DOB 1
DOB 2

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM