我有一个名为data.txt的文件,其中包含学生编号和姓名:
select convert_tz(str_to_date(left(val, 15), '%Y%m%dT%H%i%s'), '+00:00', insert(right(val, 5), 4, 0, ':'))
from (select '20080915T155300+0500' as val) x
我想要实现的是用这样的句子打印这些信息:
123, Bobbie Smith
456, Suzie Lan
789, Alex Palmer
所以我尝试做的是将data.txt上的每一行放在列表中的单独列表中:
Bobbbie Smith has student number: 123
Suzie lan has student number: 456
Alex Palmer has student number: 789
这是好方向还是我应该采用完全不同的方式?
答案 0 :(得分:1)
使用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))
答案 1 :(得分:0)
您不希望将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
语句默认为每次迭代打印一个新行
答案 2 :(得分:0)
一种方法是使用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)
答案 3 :(得分:0)
以下是使用re实现目标的几种方法:
如果您不需要存储已处理的行,只想直接打印输出:
with open("data.txt", "r") as f:
for l in f.readlines():
try:
age, name = re.findall(r'\s*(\d+),\s*(.*)', l)[0]
print('{} has student number: {}'.format(name, age))
except:
pass
如果你想将处理过的行存储为元组列表,可能会这样:
with open("data.txt", "r") as f:
lines = [v[0]
for v in [re.findall(r'\s*(\d+),\s*(.*)', l) for l in f.readlines()] if v]
for age, name in lines:
print('{} has student number: {}'.format(name, age))