【问题标题】:Formatting a textfile python格式化文本文件python
【发布时间】:2017-03-28 01:36:33
【问题描述】:

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

    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,

【问题讨论】:

  • 检查什么是block。它也可能有\n。所以它最终添加了 2 个换行符 char \n。
  • @Rohanil 它在创建时不应该有一个 \n 虽然它是正确的。
  • 你的testfile.txt好吗?我尝试了usr1:pwd1,usr2:pwd2,usr3:pwd3,usr4:pwd4,,它没有多余的行就可以正常工作。
  • 我从 testfile.txt 中提取它们,每个字符串都在一个新行上隔开。

标签: python escaping character newline


【解决方案1】:

检查什么是block。它也可能有\n。所以它最终添加了 2 个换行符 char \n。尝试不添加额外的\n 像

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

或尝试在block 上使用strip

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

【讨论】:

  • 当我在没有 \n 的情况下这样做时,它的格式如下::item1:item2:item3:item4
【解决方案2】:

好的,我假设 testfile 的内容如下:

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')

【讨论】:

  • 我只是用 abcd 作为例子,当我使用我不知道的单词列表时,我可以使用这个方法。
  • 好的,我将块更改为“单词列表”。现在上面的输出是你想要的吗?
  • 不是文字列表。我添加的字符串在格式化之前对我来说是未知的。
  • 好的,我已经进行了更改,假设 'testfile.txt' 具有特定格式
猜你喜欢
  • 2015-12-05
  • 1970-01-01
  • 1970-01-01
  • 2013-08-10
  • 2021-06-23
  • 1970-01-01
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多