Python试图截断writento文件,然后将其复制到另一个fi

2024-09-30 12:34:19 发布

您现在位置:Python中文网/ 问答频道 /正文

这是我为此编写的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+”之间更改文件模式模块,但这行不通。在

另外,我知道这是一个烦人的重复代码,但我对这一点还是很陌生的,我仍在培养缩短代码的技能。对此我深表歉意,我很感激你们中任何一个可能会回复的人的耐心。在

谢谢。在


Tags: theto代码youtargetinputrawline
1条回答
网友
1楼 · 发布于 2024-09-30 12:34:19

问题是,你没有把你的read和{}分开。在

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

但是,有更好的方法复制文件,例如:

^{pr2}$

相关问题 更多 >

    热门问题