在Python中使用文本文件中的用户信息

2024-06-28 18:50:21 发布

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

我有个文件叫数据.txt学生编号和姓名:

123, Bobbie Smith
456, Suzie Lan
789, Alex Palmer

我想要实现的是用这样的句子打印这些信息:

Bobbbie Smith has student number: 123
Suzie lan has student number: 456
Alex Palmer has student number: 789

所以我试着把每一行数据.txt在列表中的单独列表中,使用:

file = open("data.txt", "r")
studentInfo = file.readlines()
file.close()
lines = [[line] for line in studentInfo]

>>> print(lines)
[['123, Bobbie Smith\n'], ['456, Suzie Lan\n'], ['789, Alex Palmer']]

这是一个好的方向,还是我应该用一个完全不同的方式来做这件事?你知道吗


Tags: 数据txtnumber列表studentfilehassmith
3条回答

使用csv避免条带线。你知道吗

import csv

with open('data.txt', 'r', encoding='utf-8') as csv_f:
    reader = csv.reader(csv_f)

    for line in reader:
        print('{x[1]} has student number: {x[0]}'.format(x=line))

你不想用file作为变量名,因为它是一个函数。所以你基本上覆盖了它(谢谢@Mark Tolonen)。你知道吗

您可以稍微修改它,然后使用上下文管理器读取文件,并使用string.format以可读的方式打印数据

with open("data.txt", "r") as f:
    lines = [line.split(',') for line in f.readlines()]

for s in lines:
    print '{} has student number: {}'.format(s[1].strip(), s[0].strip())

输出:

Bobbie Smith has student number: 123
Suzie Lan has student number: 456
Alex Palmer has student number: 789

我正在从行中剥离新行,因为print语句在默认情况下为每个迭代打印新行

一种方法是使用numpy库

import numpy as np

x, y = np.loadtxt("data.txt", dtype = str, delimiter = ',', unpack = True)
for (i,j) in zip(x,y):
print(j+" has student number: "+i)

相关问题 更多 >