一部のデータを再フォーマットして、Python で出力ファイルに保存しようとしています。元の行から各行を .strip() し、リストに追加します。元のデータに追加する必要がある値を含む 2 番目のリストを作成し (変更は元のデータを囲みます)、それを繰り返し処理して、文字列書式演算子を使用して変更されたデータを出力ファイルに書き込みます。元データ一覧です。出力では、出力の各レコードに一度だけ提示される情報を挿入する必要があるため、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 を印刷すると、問題の要素に が表示されたnowhitespace.pop(0)
ときだけでなく、繰り返しごとに Python が format ステートメントで操作を実行していることがわかります。{0}
元の情報を文字列データに渡す、または.pop()
操作がすべての要素で発生しないようにする、より適切な方法はありますか?