将文件内容从源复制到目标是应用程序中的一种常见用例。
Python提供了简单且内置模块,以便将文件从源复制到目的地。 模块(附)还负责优雅地关闭文件流,并确保在使用文件资源的代码完成执行时,将清理资源。
with语句阐明了以前将使用try ... finally块的代码,以确保执行代码清除。
步骤1:读取源文件位置和文件名
-bash-4.2$ python3 Python 3.6.8 (default, Apr 25 2019, 21:02:35) [GCC 4.8.5 20150623 (Red Hat 4.8.5-36)] on linux Type "help", "copyright", "credits" or "license" for more information. >>> import os >>> src_file = 'orig_filel.txt' >>> src_dir = os.getcwd()>>> src_file_location = os.path.join(src_dir, src_file)>>> print(src_file_location)/home/user/Desktop/my_work/orig_filel.txt
步骤2:读取目标文件的位置和文件名
>>> dest_file_location = os.path.join(src_dir, 'dest_file.txt') >>> print(dest_file_location)/home/user/Desktop/my_work/dest_file.txt
步骤3:读取源文件内容(可选)
>>> with open(src_file_location) as f: ... for line in f: ... print(line)... this is the original file
步骤4:将源文件内容写入目标文件
>>> with open(src_file_location, 'r') as f1: ... with open(dest_file_location, 'w') as f2: ... for line in f1: ... f2.write(line)...
步骤5:读取目标文件内容(可选)
>>> with open(dest_file_location) as f1: ... for line in f1: ... print(line)... this is the original file