バグと思われる原因を解明しようとして、最終的に Python 2.7 のraw_input()関数の奇妙な動作に遭遇しました。
ファイルの内容を (クリップボード経由で) 手動でコピーした結果の文字列のみから、CR LFのペアのCR文字を削除します。raw_input()に渡された文字列は、以前のものと同じ文字列の表示のコピーであり、CR文字が失われません。単独のCR文字は、すべての場合で変更されません。CR (キャリッジ リターン) は\r文字です。
混乱した説明よりも明確にするために、注文を実行するだけでよいという事実を観察するために何をしなければならないかを説明するコードを次に示します。
ポイントはTextオブジェクトにあります。 Textを作成するためにraw_input()に渡された 8 文字ではなく、7 文字です。
raw_input()に渡された引数が実際に 8 文字であることを確認するために、同じ引数で別のファイルPASTED.txtを作成しました。Notepad ++ウィンドウでのコピーが私に示したように、この問題で何かを確認するのは確かに厄介な作業です:あらゆる種類の行末(\r、\n、\r\n)は端にCR LFとして表示されますそのようなウィンドウ内の行の。
ファイルのデータ全体を選択するには、Ctrl-A をお勧めします。
コーディングや理解の間違いを犯したのか、それとも Python の本当の機能なのか、当惑しています。
あなたからの解説と光を願っています。
with open('PRIM.txt','wb') as f:
f.write('A\rB\nC\r\nD')
print " 1) A file with name 'PRIM.txt' has just been created with content A\\rB\\nC\\r\\nD"
raw_input(" Open this file and copy manually its CONTENT in the clipboard.\n"+\
" --when done, press Enter to continue-- ")
print "\n 2) Paste this CONTENT in a Notepad++ window "+\
" and see the symbols at the extremities of the lines."
raw_input(" --when done, press Enter to continue-- ")
Text = raw_input("\n 3) Paste this CONTENT here and press a key : ")
print (" An object Text has just been created with this pasted value of CONTENT.")
with open('PASTED.txt','wb') as f:
f.write('')
print "\n 4) An empty file 'PASTED.txt' has just been created."
print " Paste manually in this file the PRIM's CONTENT and shut this file."
raw_input(" --when done, press Enter to continue-- ")
print "\n 5) Enter the copy of this display of A\\rB\\nC\\r\\nD : \nA\rB\nC\r\nD"
DSP = raw_input('please, enter it on the following line :\n')
print " An object DSP has just been created with this pasted value of this copied display"
print '\n----------'
with open('PRIM.txt','rb') as fv:
verif = fv.read()
print "The read content of the file 'PRIM.txt' obtained by open() and read() : "+repr(verif)
print "len of the read content of the file 'PRIM.txt' ==",len(verif)
print '\n----------'
print "The file PASTED.txt received by pasting the manually copied CONTENT of PRIM.txt"
with open('PASTED.txt','rb') as f:
cpd = f.read()
print "The read content of the file 'PASTED.txt' obtained by open() and read() "+\
"is now : "+repr(cpd)
print "its len is==",len(cpd)
print '\n----------'
print 'The object Text received through raw_input() the manually copied CONTENT of PRIM.txt'
print "value of Text=="+repr(Text)+\
"\nText.split('\\r\\n')==",Text.split('\r\n')
print 'len of Text==',len(Text)
print '\n----------'
print "The object DSP received through raw_input() the copy of the display of A\\rB\\nC\\r\\nD"
print "value of DSP==",repr(DSP)
print 'len of DSP==',len(DSP)
私のOSはWindowsです。他のオペレーティングシステムでも同じことが観察されるのだろうか。