在文件复制的过程中,需要判断文件是否存在,这时就要用exists函数。这个命令将文件名字符串作为参数,如果文件存在的话,它将返回True,否则将返回False。
总之,复制文件主要分为以下几个步骤:
1.打开源文件(使用open函数)
2.读出源文件内容并赋值到变量1中(使用read函数)
3.判断目标文件是否存在(这一步亦可以省略)(使用exists函数)
4.打开目标文件(使用open函数)
5.将变量1中的内容写入到目标文件中(使用write函数)
6.关闭源文件和目标文件(使用close函数)

具体代码如下:

from sys import argv
from os.path import exists#引入exists函数

script, from_file, to_file = argv
print("Copying from %s to %s" %(from_file, to_file))

#打开文件,读出文件内容,并赋值给indata
input1 = open(from_file)
indata = input1.read()

print("The input file is %d bytes long" %len(indata))
print("Dose the output file exists? %r" %exists(to_file))
#上面的exists()函数主要是用作文件存在性判断。这个命令将文件
#名字符串作为参数,如果文件存在的话,它将返回True,否则将
#返回False
print("Ready,hit RETURN to continue, CTRL-C to abort.")
input()

output = open(to_file, 'w')#'w'代表只写,文件不存在则自动创建
output.write(indata)
print("Alright, all done")

output.close()
input1.close()

代码运行结果如图:

python 复制功能 python的复制命令_python 复制功能

python 复制功能 python的复制命令_字符串_02