知识点:
1. os.path和exists:os和sys一样是Python自带基本库之一,os.path模块主要用于文件的属性获取,其中exists()得作用是将文件名作为参数进行判定,如果文件存在则返回True,否则返回Flase,参照第16行代码;
2.len():以文件名为参数,以数值的形式返回该文件的长度,参照第14行代码;
3.将文件内容copy到另外一个文件;
基础练习:
from sys import argv
#从os.path导入exists函数
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}.")
#we could do these two on one line, how?
in_file = open(from_file)
indata = in_file.read()
#len()以数值的形式返回文件的长度
print(f"The input file is {len(indata)} bytes long")
#exists()将文件名作为参数进行判定,如果文件存在则返回True,否则返回Flase
print(f"Does the output file exists? {exists(to_file)}")
print("Ready, hit RETURN to continue, CTRL-C to abort.")
input()
out_file = open(to_file,'a')
out_file.write(indata)
print("Alright, all done.")
out_file.close()
in_file.close()
结果:
程序运行成功,文件也复制过去了,还有注意第16行代码的运行结果,哪怕输出文件不存在,程序也会创建一个,不过是普通文件;
源文件(from_file)
目标文件(to_file)
实际上我的代码和Zed的是有点不一样的,我在open()文件时用了追加模式, 第20行代码;
折腾一下:
1.不要让程序在复制之前提问了,让它直接复制;我把注释和没必要的全删掉了
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print(f"Copying from {from_file} to {to_file}.")
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 exists? {exists(to_file)}")
out_file = open(to_file,'a')
out_file.write(indata)
print("Alright, all done.")
out_file.close()
in_file.close()
结果不贴了,反正是对的;
2.尽量改短代码,终极目标改成1行;记住,目标是拷贝文件;
from sys import argv
script, from_file, to_file = argv
open(to_file,'a').write(open(from_file).read())
正常情况下我只能这样了,后面没有close()是因为这样写的话,程序执行read()之后文件就会被关闭;
然后非正常情况可以写成这样↓↓↓
from sys import argv;script, from_file, to_file = argv;open(to_file,'a').write(open(from_file).read())
这样真的可以执行啊,就是在每行之间加个英文分号“;”代替换行,Zed真会玩!
为什么要 写out_file.close()?
以下内容来自@哈哈餐馆的博客,我通常学完几课都要去他的博客逛一下,将学习记录在博客上的想法也是来自他的博客:
原因在于如果不写,则新复制的文件中是不会保存任何内容的。也就是没有保存(如同在 16 题 Zed 介绍的一样)
out_file = open(to_file, 'w')
执行时会创建 to_file 文件,但是没内容out_file.write(indata)
执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。
只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率(特别在特大文件的时候)那么为什么在 精简练习、极限精简练习 中不需要关闭呢?
我的理解:
关键点在于没有使用变量,也就是没有个打开的文件起名字。
这个时候,任何操作是一次性的,我们没办法在写入了一些东西后再说“喂,就你,你再写入这些内容”,python 不知道这句‘喂’说的是哪一个内存堆栈中的数据。
所有没有其名的代码都是一次性的,不会保存在内存中,针对 open 来说,python 就自动关闭它了。