这是我为此目的编写的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中运行时,会出现这种情况:
We're going to erase 'test.txt'.
If you don't want that, hit CTRL-C (^C).
If you do want that, hit RETURN.
?
Opening the file...
Truncating the file. Goodbye!
Now I'm going to ask you for three lines.
line 1: h
line 2: h
line 3: h
I'm going to write these to the file.
Now we are going to copy 'test.txt' to 'test4.txt'!
And finally, we close it.
然而 - 一旦我跑:
cat test4.txt
在Windows Powershell中,这是它输出的内容 - 在以下行之后没有任何内容,尽管该空白空间在以下行后面的Powershell页面34行中显示:
PS C:\python27> cat test4.txt
我尝试更改' r +'之间的文件模式模块。并且' w +'整个Python代码,但这不起作用。
另外 - 我知道这是烦人且重复的代码,但我对此很陌生,并且仍在提高我缩短代码的技能。为此道歉,我感谢任何可能回复的人的耐心。
感谢。
答案 0 :(得分:1)
问题是,您没有将read
和write
分开。
将缓冲区写入文件后,文件指针位于文件末尾。如果再次使用read()
,则告诉文件描述符从该点读取,即从文件末尾读取。当然没有什么可读的......所以你什么都没得到; - )
尝试将您的写入/读取分开或将文件描述符再次放到开头(使用seek
),然后就完成了。
还可以使用with
语句来简化代码并将相关的行放在一起。
这是更新的脚本,有一个更好的解决方案:
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 "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 "Opening the file..."
with open(filenamefrom, 'w+') as target_file:
print "Truncating the file. Goodbye!"
target_file.truncate()
print "I'm going to write these to the file."
target_file.write('%r\n%r\n%r\n' % (line1, line2, line3))
print "Now we are going to copy %r to %r!" % (filenamefrom, filenameto)
with open(filenamefrom, 'r') as target_file:
readdata = target_file.read()
with open(filenameto, 'w+') as to_file:
to_file.write(readdata)
但是,有更好的方法可以复制文件,例如:
from shutil import copyfile
copyfile(filenamefrom, filenameto)