【发布时间】:2013-05-10 21:09:51
【问题描述】:
我正在尝试重新格式化一些数据并将其保存到 python 中的输出文件中。我 .strip() 原始的每一行并将其附加到列表中。我创建了第二个列表,其中包含我需要添加到原始数据的值(修改包含原始数据)并在我需要从原始数据列表。输出需要在输出的每条记录中插入一些仅出现一次的信息,因此它不是 1:1 输出(原始行到输出行),我相信这就是我遇到问题的地方。这是我的代码示例...
原始数据:
Client
#ofrecords(as an integer)
Line1ofrecord1
Line2ofrecord1
....
Line1ofrecord2
Line2ofrecord2
....
End
代码:
def shouldbesimple(originalfile):
inputfile = open(originalfile, "r")
outputfile = open('finaloutput.txt', "w")
nowhitespace = originalfile.strip()
Client = nowhitespace.pop(0)
Counter = nowhitespace.pop(0) (each record has exactly the same number of lines)
#at this point only record information remains in list..
Header = "stuff at beginning of each record in output"
Insertclient = "NEEDED {1} CHANGES"
Line1 = "THINGS I {0} MUST ADD"
Footer = "stuff at end of each record in output"
thingstoadd = [Header, Line1, Insertclient, Footer]
while counter > 0 :
writetofile = ""
for element in thingstoadd:
writetofile = element.format(nowhitespace.pop(0), Client)
outputfile.write(writetofile + "\n")
counter = counter - 1
inputfile.close()
outputfile.close()
在我开始迭代要添加的东西之前,一切都按预期工作..
数据未按预期排列,我收到“从空列表中弹出”错误。打印 writetofile 显示 python 在每次迭代时都在 format 语句中运行 nowhitespace.pop(0) 操作,而不仅仅是当 {0} 出现在相关元素中时。
有没有更合适的方法将原始信息传递到字符串数据中,或者防止.pop()操作在每个元素上发生?
【问题讨论】:
-
请将您的代码放在一个代码块中(缩进四个空格)。我根本看不懂这段代码。
-
感谢您的忍者编辑。当我试图提交自己的作品时,我感到很震惊。这是我的第一篇文章,所以我提前为我缺乏适当的礼仪道歉。我会尽快回答任何问题。
-
您打算拨打
nowhitespace = originalfile.strip()做什么?在我看来originalfile是你的文件名;打电话给strip很奇怪,更奇怪的是稍后再尝试pop。 -
首先,请给我们实际的异常,带回溯,而不是试图描述错误以及何时发生。
-
我想避免如果原始文件在每行数据的开头或结尾有额外空间可能出现的任何问题。输出在字符串中内置了间距,我在 originalfile 的每一行周围“环绕”。
标签: python list iteration string-formatting