这是我为此编写的Python代码:
from sys import argv
from os.path import exists
script, filenamefrom, filenameto = argv
print "We're going to erase %r." % filenamefrom
print "If you don't want that, hit CTRL-C (^C)."
print "If you do want that, hit RETURN."
raw_input("?")
print "Opening the file..."
target = open(filenamefrom,'w+')
print "Truncating the file. Goodbye!"
target.truncate()
print "Now I'm going to ask you for three lines."
line1 = raw_input("line 1: ")
line2 = raw_input("line 2: ")
line3 = raw_input("line 3: ")
print "I'm going to write these to the file."
target.write('%r\n%r\n%r\n' % (line1, line2, line3))
print "Now we are going to copy %r to %r!" % (filenamefrom, filenameto)
readdata = target.read()
openfilenameto = open(filenameto,'w+')
openfilenameto.write(readdata)
print "And finally, we close it."
openfilenameto.close()
target.close()
现在,当我在Powershell中运行此程序时,会出现以下情况:
^{2}$不过,一旦我跑了:
cat test4.txt
在Windows Powershell中,这是它输出的内容-下一行后面没有任何内容,尽管在下一行后面的Powershell页面34行后面会有空白:
PS C:\python27> cat test4.txt
我尝试过在整个Python代码中在“r+”和“w+”之间更改文件模式模块,但这行不通。在
另外,我知道这是一个烦人的重复代码,但我对这一点还是很陌生的,我仍在培养缩短代码的技能。对此我深表歉意,我很感激你们中任何一个可能会回复的人的耐心。在
谢谢。在
问题是,你没有把你的}分开。在
read
和{将缓冲区写入文件后,文件指针位于文件末尾。如果您再次使用
read()
,则告诉文件描述符从该点读取,即从文件末尾读取。当然没有什么可看的…所以你什么也得不到;-)尝试将写/读分开,或者再次将文件描述符放在开头(用
seek
),就完成了。在还可以使用
with
语句来简化代码并将相关行组合在一起。在以下是更新后的脚本,其中有一个更好的解决方案:
但是,有更好的方法复制文件,例如:
^{pr2}$相关问题 更多 >
编程相关推荐