使用python排列文本文件

时间:2018-08-01 17:13:18

标签: python linux python-2.7 file

嘿,我想使用python安排文本文件。我的python代码运行正常,但没有给我期望的答案。让我解释 我有一个像这样的文本文件:-

serial
name
phone 
gmail
1
blah blah
55555
blah@blah.com

我这样写我的脚本:-

out=open('out.txt','w')  
with open('blah.txt') as b:
    i=1
    for line in b:
        if i==1:
            out.write(line)
            i=i+1
        elif type(line)==int:
            out.write('\n'+line)
        elif type(line)==str:
            out.write('\b\t'+line)
        else:
            pass
out.close()

我没有编写整个程序,但是就像这样。但这使我的输出与输入相同。我想念什么吗?

我期望的答案是:-

serial    name      phone   gmail
1        blah blah   55555   blah@blah.com

3 个答案:

答案 0 :(得分:1)

您正在尝试将文本行转换为列。该代码假设您的文件blah.txt中具有相同数量的标题和值:

with open('blah.txt', 'r') as f_in, open('out.txt','w',newline='') as f_out:
    lines = [l.strip() for l in f_in.readlines()]
    headers, values = lines[:len(lines)//2], lines[len(lines)//2:]
    for h in headers:
        f_out.write(h + '\t\t')
    f_out.write('\n')
    for v in values:
        f_out.write(v + '\t\t')
    f_out.write('\n')

由此out.txt将是:

serial      name        phone       gmail       
1       blah blah       55555       blah@blah.com   

答案 1 :(得分:1)

您可以使用str.center()进行对齐,并且在写了一半的行之后需要添加\ n:

minimal verifyable complete example创建测试文件:

text ="""serial
name
phone 
gmail
1
blah blah
55555
blah@blah.com"""

fn = "t.txt"

with open(fn,"w") as f:
    f.write(text)

处理文件:

fn = "t.txt"

lines = []
with open(fn,"r") as f:
    lines = [x.strip() for x in f.readlines()]

# what is the longest data  items? space others accordingly:
longest = max(len(x) for x in lines)

with open("t2.txt","w") as f: 
    # write first half of rows
    for header in lines[:(len(lines)//2)]:
        f.write( str.center( header, longest+2))
    f.write("\n")
    # write second half of rows
    for data in lines[len(lines)//2:]:
        f.write( str.center( data, longest+2))
    f.write("\n")

读回并输出以进行验证:

print("\n")
with open("t2.txt","r") as r:
    print(r.read())

输出:

   serial          name          phone          gmail     
     1          blah blah        55555      blah@blah.com 

答案 2 :(得分:-2)

您没有关闭输出文件:

尝试在末尾添加out.close()