【发布时间】: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