Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/343.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 试图覆盖文件时,原始数据会被删除,但不会被替换_Python - Fatal编程技术网

Python 试图覆盖文件时,原始数据会被删除,但不会被替换

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

我是一个初学者,正在学习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"

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)
没有返回值。@user5169396
seek
只移动文件指针-您需要移动它然后读取,移动本身不会返回anything@jonrsharpe我想你可以在
阅读
时将其作为一个有更多解释的答案发布。你已经在文件末尾了。请尝试
seek(0)
首先。在def中更改为打印文件.seek(0)时,输出仅为“无”。:(
输出文件.seek(0)
然后
打印文件.read()
输出文件.seek(0)
没有返回值。@user5169396
seek
只移动文件指针-您需要移动它然后读取,移动本身不会返回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: