Python - 尝试截断、写入然后将写入的文件复制到另一个文件

Python - Trying to truncate, write to and then copy the written-to file to another file

这是我为此目的编写的 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 中,这就是它输出的内容 - 在下一行之后没有任何内容,尽管空 space 在 Powershell 页面下行后的第 34 行:

PS C:\python27> cat test4.txt

我曾尝试在整个 Python 代码中更改 'r+' 和 'w+' 之间的文件模式模块,但这不起作用。

此外 - 我知道这是烦人且重复的代码,但我对此很陌生,并且仍在培养缩短代码的技能。对此深表歉意,我感谢任何可能回复的人的耐心等待。

谢谢。

问题是,您没有将 readwrite 分开。

将缓冲区写入文件后,文件指针位于文件末尾。如果再次使用 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)