文章目录
ex17
这一节的内容是将一个文件中的内容复制到另外一个文件中。
code
from sys import argv
from os.path import exists # 引入os.path模块
script, from_file, to_file = argv, "test.txt", "ex15_sample.txt"
print(f"Copying from {from_file} to {to_file}")
in_file = open(from_file)
indata = in_file.read() # 在变量in_file后调用read函数(读取文件内容)
print(f"The input file is {len(indata)} bytes long") # len()函数以数值形式返回呢传递的字符串长度
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') # 用open以写入模式打开to_file变量,并将该文件放入变量out_file,
# 若无该文件则自动创建一个
out_file.write(indata) # 在变量out_file后调用write函数,写入变量indata的内容
print("Alright, all done.")
out_file.close()
in_file.close()
result
Copying from test.txt to ex15_sample.txt
The input file is 14 bytes long
Does the output file exist?True
Ready, hit RETURN to continue, CTRL-C to abort.
RETURN
Alright, all done.
代码没有输出复制后文件的指令,所以没有打印出来,但是可以看到文件的复制结果。
加分习题:
Q1.这个脚本实在是有点烦人。没必要在做复制之前问你,也没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。
友好的脚本:
from sys import argv
script, from_file, to_file = argv, "test.txt", "ex15_sample.txt"
indata = open(from_file).read() # 在变量in_file后调用read函数(读取文件内容)
out_file = open(to_file, 'w') # 用open以写入模式打开to_file变量,并将该文件放入变量out_file,
# 若无该文件则自动创建一个
out_file.write(indata) # 在变量out_file后调用write函数,写入变量indata的内容
print(f"Alright, all done.The input file is {len(indata)} bytes long.") # len()函数以数值形式返回呢传递的字符串长度
result
Alright, all done.The input file is 14 bytes long.
Q2.看看你能把这个脚本改多短,我可以把它变成一行。
看了网上很多大神的,我只能精简的3行
from sys import argv
script, from_file, to_file = argv, "test.txt", "ex15_sample.txt"
open(to_file, 'w').write(open(from_file).read())
# 用open函数以写入模式打开变量to_file, 并写入用open函数以读取模式打开from_file文件的内容
result
E:\code\venv\Scripts\python.exe E:/code/ex17.py
Process finished with exit code 0
Q3.在“应该看到的结果”中我使用了一个叫cat的东西,这个古老的命令的用途是将两个文件“拼接”到一起,不过实际上它最大的用途是打印文件内容到屏幕上。你可以通过man cat命令了解到更多信息。
?
> man cat
名称
Get-Content
语法
Get-Content [-Path] <string[]> [<CommonParameters>]
Get-Content [<CommonParameters>]
别名
gc
cat
type
备注
Get-Help 在此计算机上找不到该 cmdlet 的帮助文件。它仅显示部分帮助。
-- 若要下载并安装包含此 cmdlet 的模块的帮助文件,请使用 Update-Help。
-- 若要联机查看此 cmdlet 的帮助主题,请键入: "Get-Help Get-Content -Online" 或
转到 https://go.microsoft.com/fwlink/?LinkID=113310。
Q4.找出为什么需要在代码中写output.close()
这里我直接引用CSDN上大神写的回答吧:
原因在于如果不写,则新复制的文件中是不会保存任何内容的。
out_put = open(to_file, ‘w’) 执行时会创建 to_file 文件,但是没内容
out_put.write(indata) 执行时,内容会写入到 to_file 的内存数据中,但仍未写入硬盘。
只有在执行 close 时 python 才指定文本的各种操作已经结束了,不会再有任何变化,这个时候在写入硬盘可以尽可能地减少硬盘读写操作,提高效率(特别在特大文件的时候)
那么为什么在 精简练习、极限精简练习 中不需要关闭呢?
我的理解:
关键点在于没有使用变量,也就是没有个打开的文件起名字。
这个时候,任何操作是一次性的,我们没办法在写入了一些东西后再说“喂,就你,你再写入这些内容”,python 不知道这句‘喂’说的是哪一个内存堆栈中的数据。
所有没有其名的代码都是一次性的,不会保存在内存中,针对 open 来说,python 就自动关闭它了。
Q5.阅读一下与Python的import语句相关的内容,打开python测试一下。试着导入一些东西,看看你能不能弄对,弄不对也没关系。