为了弄清楚似乎是一个错误的原因,我终于遇到了Python 2.7中raw_input()函数的一个奇怪行为:
它仅从文件内容的手动复制(通过剪贴板)产生的字符串中删除对CR LF的CR字符。传递给raw_input()的字符串是与以前的字符串相同的字符串的显示副本,它们不会丢失它们的CR字符。在所有情况下,单独的CR字符都保持不变。CR(回车)是一个\ r字符。
为了比混乱的描述更清楚,这里有一段代码描述了必须做什么来观察事实,只需要执行其命令。
重点在于Text对象:它有 7 个字符,而不是传递给raw_input()以创建Text的 8 个字符。
为了验证传递给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)
我的操作系统是 Windows。我想知道在其他操作系统上是否也观察到相同的情况。