简体   繁体   English

Python读取文件并将其解析为带空格的变量

[英]Python reading in a file and parsing it to variables with whitespaces

I have a text file (Students.txt) i need to read into python and parse them into variables first_name, middle_name, last_name, student_id. 我有一个文本文件(Students.txt),我需要读入python并将其解析为变量first_name,middle_name,last_name,student_id。 The first few lines of the text file is as shows: 文本文件的前几行如下所示:

Last Name  Midle Name  First Name   Student ID  
----------------------------------------------
Howard     Joe          Moe         howar1m     
Howard                  Curly       howar1c     
Fine       Ken          Lary        fine1l   

The code I've tried 我尝试过的代码

f = open("Students.txt")
for line in f:
    fields = line.strip().split()
    last_name = fields[0]

Only works for last name, because if I try fields[1] for middle name, I get a "list index out of range" error. 仅适用于姓氏,因为如果我尝试将fields[1]用作中间名,则会收到“列表索引超出范围”错误。 I've tried using if not line.startswith('Middle Name'): continue but it doesn't recognize the column. 我试过使用, if not line.startswith('Middle Name'): continue但无法识别该列。 Does anyone have a better approach as to how to parse these into their respective variables? 关于将它们解析为各自的变量,是否有人有更好的方法?

Probably you should use readlines(), and then loop over each line with skipping first 2 rows. 可能应该使用readlines(),然后通过跳过前两行来遍历每一行。 Hence the code will look like 因此,代码看起来像

f = open("Student.txt")
lines = f.readlines()
print lines
for line in lines[2:]:
    fields = line.split()
    last_name = fields[0]
    middle_name = fields[1]

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

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