The file name is studs.txt and this is what is inside:
12345 2 G400 Bart Simpson
12346 1 GH46 Lisa Simpson
12347 2 G401 Homer J Simpson
12348 4 H610 Hermione Grainger
12349 3 G400 Harry Potter
12350 1 G402 Herschel Shmoikel Krustofski
13123 3 G612 Wayne Rooney
x = input("Enter a filename: ")
try:
o = open(x, "r")
p = o.read()
y = tuple(j for j in p.splitlines())
m = " ".join(map(str, y))
print(m)
o.close()
except IOError as e :
print("File Does Not Exist")
当我运行此代码时,它将导入此文件" studs.txt"并把它放入一个字符串,但我想将该字符串转换为表格式和特定的布局,以使它看起来像这样:
Simpson, Bart 12345 G400 2
Simpson, Lisa 12346 G401 1
等等
答案 0 :(得分:0)
我认为你可以这样做:
try:
o = open(x, "r")
p = o.read()
y = tuple(j.split() for j in p.splitlines())
#m = " ".join(map(str, y))
for v1,v2,v3,fname,*rest_of_name in y:
#print(v1,v2,v3,fname,*rest_of_name)
if int(v1) != some_year:
continue;
print("{:<30} {:<10} {:<5} {:<5}".format(fname + ', ' + ' '.join(rest_of_name), v1,v3, v2))
o.close()
except IOError as e :
print("File Does Not Exist")
打印:
Bart, Simpson 12345 G400 2
Lisa, Simpson 12346 GH46 1
Homer, J Simpson 12347 G401 2
Hermione, Grainger 12348 H610 4
Harry, Potter 12349 G400 3
Herschel, Shmoikel Krustofski 12350 G402 1
Wayne, Rooney 13123 G612 3