Python 试图覆盖文件时,原始数据会被删除,但不会被替换
我是一个初学者,正在学习Python 我创建这个函数是为了练习函数编写。我明白没有必要这样写 我的问题是,out_文件数据被删除,而不是替换为预期的in_文件数据Python 试图覆盖文件时,原始数据会被删除,但不会被替换,python,Python,我是一个初学者,正在学习Python 我创建这个函数是为了练习函数编写。我明白没有必要这样写 我的问题是,out_文件数据被删除,而不是替换为预期的in_文件数据 from sys import argv script, in_file, out_file = argv print "Copying from filename '%s' to filename '%s'" % (in_file, out_file) print "The input data reads as: \n" i
from sys import argv
script, in_file, out_file = argv
print "Copying from filename '%s' to filename '%s'" % (in_file, out_file)
print "The input data reads as: \n"
in_file = open(in_file)
print in_file.read()
print "The file to be overwritten originally reads as \n"
out_file = open(out_file, 'w+')
print out_file.read()
print "Now, to practice function writing, we will use one to overwrite:"
def overwrite():
out_file.write(in_file.read())
print out_file.read()
print "The overwritten file now reads as:\n"
overwrite()
因此,>python ex20.py cat.txt dog.txt的输出是:(其中dog.txt=“dogs是最好的”,cats.txt=“cats是最好的”)
当您
读取时
您已经在文件末尾了。首先尝试seek(0)
。在def中更改为打印文件.seek(0)时,输出仅为“无”:(输出文件.seek(0)
然后输出文件.read()
输出文件.seek(0)
没有返回值。@user5169396seek
只移动文件指针-您需要移动它然后读取,移动本身不会返回anything@jonrsharpe我想你可以在阅读时将其作为一个有更多解释的答案发布。你已经在文件末尾了。请尝试seek(0)
首先。在def中更改为打印文件.seek(0)时,输出仅为“无”。:(输出文件.seek(0)
然后打印文件.read()
输出文件.seek(0)
没有返回值。@user5169396seek
只移动文件指针-您需要移动它然后读取,移动本身不会返回anything@jonrsharpe我想你可以把它作为一个有更多解释的答案贴出来
Copying from filename 'cat' to filename 'dog'
The input data reads as:
cats are the best
The file to be overwritten originally reads as
Now, to practice function writing, we will use one to overwrite:
The overwritten file now reads as: