【发布时间】:2012-12-07 16:41:06
【问题描述】:
所以我有多个格式如下的 txt 文档:
james
M
18
72
170
teresa
F
19
63
115
有些只有两个名称,有些只有 50 个。基本上,我要做的是格式化信息,以便将其重写为具有以下格式的新文本文件:
Name: james
Gender: M
Age: 18
Height: 72
Weight: 170
Name: teresa
Gender: F
Age: 19
Height: 63
Weight: 115
到目前为止,我有:
def tagInfo(fileName):
with open(fileName) as infile, open("altered.txt","w") as outfile:
for i,line in enumerate(infile):
if i == 0:
outfile.write("Name: "+line.strip()+"\n")
if i == 1:
outfile.write("Gender: "+line.strip()+"\n")
if i == 2:
outfile.write("Age: "+line.strip()+"\n")
if i == 3:
outfile.write("Height: "+line.strip()+"\n")
if i == 4:
outfile.write("Weight: "+line.strip()+"\n")
outfile.close()
这个程序所做的只是编辑前 5 行。我正在努力做到这一点,所以如果我给它一个 50 人要更改的列表,它会更改所有 50 人的信息,而不仅仅是前五行。使用我目前的解决方案,这是不可能的。我不知道从哪里开始,我觉得最好放弃一切并采取不同的方法。
你们有什么解决办法吗?
【问题讨论】:
-
与您的问题并不真正相关,但我很惊讶没有人指出
outfile.close()是多余的。使用 with 语句的全部意义在于文件上下文管理器将在退出 with 语句块时关闭文件。
标签: python io python-3.x