笨方法学Python-习题17-更多文件操作

这道习题中,我们将看到使用Python实现一个非常常见的功能,文件内容的拷贝,把A文件的内容拷贝到B文件。

#!/usr/bin/env python3 
# -*- coding: utf-8 -*-

from sys import argv
from os.path import exists

script, from_file, to_file = argv

print(f"Copying from {from_file} to {to_file}")

# we cloud do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()

print(f"The input file is {len(indata)} bytes long")

print(f"Does the output file exist? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()

out_file = open(to_file, 'w')
out_file.write(indata)

print("Alright, all done.")

out_file.close()
in_file.close()

运行ex17,结果如下:

ex17运行结果

ex17中的程序,主要流程:

  1. 打开源文件,读取源文件内容;
  2. 打开目标文件,写入源文件内容;
  3. 关闭云文件和目标文件。

出现的前面未曾见过的知识点有:

  1. len函数,用于计算源文件内容大小;
  2. exists函数,用于判断文件是否存在。

小结

  1. 利用文件读写操作实现文件内容的拷贝。

你可能感兴趣的:(笨方法学Python-习题17-更多文件操作)