编辑不同长度的txt文件中的行

时间:2012-12-07 16:41:07

标签: python io python-3.x

所以我有多个格式如下的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个人的信息,而不仅仅是前五行。根据我目前的解决方案,这是不可能的。我不知道从哪里开始,我觉得最好废弃一切并采取不同的方法。

你们有什么解决方案吗?

4 个答案:

答案 0 :(得分:3)

如果您的文件具有固定的字段列表,则将字段定义为列表,并使用带有模数的行号作为索引来获取字段名称:

fields = ('Name', 'Gender', 'Age', 'Height', 'Weight')

def tagInfo(fileName):
    with open(fileName) as infile, open("altered.txt","w") as outfile:
        for i, line in enumerate(infile):
            field = fields[i % len(fields)]
            outfile.write('{0}: {1}\n'.format(field, line))

如果超过5,您可以根据需要添加字段。

答案 1 :(得分:1)

将您的支票更改为i % 5 == 0等。这样,每隔五行检查一次就会返回。

if i % 5 == 0:
    outfile.write("Name: "+line.strip()+"\n")
elif i % 5 == 1:
    outfile.write("Gender: "+line.strip()+"\n")
elif i % 5 == 2:
    outfile.write("Age: "+line.strip()+"\n")
elif i % 5 == 3:
    outfile.write("Height: "+line.strip()+"\n")
elif i % 5 == 4:
    outfile.write("Weight: "+line.strip()+"\n")

答案 2 :(得分:1)

解决方案

修改后的解决方案

只需使用mod,简短而简单:

def tagInfo(fileName):
    with open(fileName) as infile, open("altered.txt","w") as outfile:
        for i,line in enumerate(infile):
            if i % 5 == 0:
                outfile.write("Name: "+line.strip()+"\n")
            elif i % 5 == 1:
                outfile.write("Gender: "+line.strip()+"\n")
            elif i % 5 == 2:
                outfile.write("Age: "+line.strip()+"\n")
            elif i % 5 == 3:
                outfile.write("Height: "+line.strip()+"\n")
            elif i % 5 == 4:
                outfile.write("Weight: "+line.strip()+"\n")
    outfile.close()


重写解决方案

这个解决方案会更好,因为它会消除代码中的大量欺骗,更不用说让它更清晰了:

fields = ("Name", "Gender", "Age", "Height", "Weight") # can be edited as per req.s
l = len(fields)

def tagInfo(fileName):
    with open(fileName) as infile, open("altered.txt","w") as outfile:
        for (index, s) in enumerate(infile):
             field = fields[index % l]
             outfile.write("{}: {}\n".format(field, s.strip())
    outfile.close()


mod函数

来自docs

  

%(modulo)运算符从第一个参数除以第二个参数得到余数。数字参数首先转换为通用类型。零右参数会引发ZeroDivisionError异常。参数可以是浮点数,例如,3.14%0.7等于0.34(因为3.14等于4 * 0.7 + 0.34。)模运算符总是产生与第二个操作数(或零)具有相同符号的结果;结果的绝对值严格小于第二个操作数的绝对值。


TL; DR:

  

modulo function(也称为mod函数)基本上只给出了除第一个no的余数。到了第二个。所以a % b = cmp(b, 0) * abs(a - (a // b))(我认为)。

答案 3 :(得分:0)

另一种调查问题的方法

fields = ('Name', 'Gender', 'Age', 'Height', 'Weight')
with open("infile.txt") as fin, open("altered.txt","w") as fout:
    while True:
        data =  ''.join(map(':'.join,zip(fields,fin)))
        if data:
            fout.write(data)
        else:
            break