格式化文本文件python

时间:2017-03-28 01:36:33

标签: python escaping character newline

我正在尝试将输入格式化为这样的文本文件:

    a
    b
    c
    d

我得到的是:

    a

    b

    c

    d

这是我正在使用的代码

f = open("testfile.txt", "r")
text = f.read()
text = str(text)
looper= text.count(",")
f.close()
god= open("dog.txt","a")
god.write("Passwords:")
god.close()
for count in range(looper):
    block = ""
    first= (text.find(':'))
    second= (text.find(','))
    block= text[first:second]
    text = text[second:]
    text = text[first:]
    print (block)
    god= open("dog.txt","a")
    god.write("\n"+block)
    god.close()

我关注的代码是:

    god= open("dog.txt", "a")
    god.wring("\n"+block)
    god.close()

testing.txt的输入是:

    item1:A,
    item2:B,
    item3:C,

2 个答案:

答案 0 :(得分:0)

好的,我假设测试文件的内容如下:

key1:abcde,key2:fghij,key3:klmno,

以下是代码:

with open("testfile.txt") as f:
    text = f.read()
    looper = text.count(',')

with open("dog.txt","w") as f:
    f.write("Passwords:\n")

    for count in range(looper):
        first  = (text.find(':'))
        second = (text.find(','))
        block  = text[first+1:second]
        text   = text[second:]
        text   = text[first:]
        f.write(block + '\n')

'dog.txt'文件的内容:

Passwords:
abcde
fghij
klmno

更简单的方法(首先删除“testfile.txt”末尾的逗号):

with open("testfile.txt") as f:
    lst = f.read().strip('\n').split(',')

with open("dog.txt","w") as f:
    f.write("Passwords:\n")

    for item in lst:
        key,value=item.split(':')
        f.write(value + '\n')

答案 1 :(得分:0)

检查block是什么。它也可能有\n。因此它最终添加了2个新行char \n。尝试不添加额外的\n

god= open("dog.txt","a")
god.write(block)
god.close()

或尝试在strip

上使用block
god= open("dog.txt","a")
god.write("\n" + block.strip())
god.close()