企业🤖AI Agent构建引擎,智能编排和调试,一键部署,支持私有化部署方案 广告
# 习题 17: 更多文件操作 现在让我们再学习几种文件操作。我们将编写一个 Python 脚本,将一个文件中的内容拷贝到另外一个文件中。这个脚本很短,不过它会让你对于文件操作有更多的了解。 <table class="highlighttable"><tbody><tr><td class="linenos"> <div class="linenodiv"> <pre> 1&#13; 2&#13; 3&#13; 4&#13; 5&#13; 6&#13; 7&#13; 8&#13; 9&#13; 10&#13; 11&#13; 12&#13; 13&#13; 14&#13; 15&#13; 16&#13; 17&#13; 18&#13; 19&#13; 20&#13; 21&#13; 22&#13; 23&#13; 24</pre> </div> </td> <td class="code"> <div class="highlight"> <pre>from sys import argv&#13; from os.path import exists&#13; &#13; script, from_file, to_file = argv&#13; &#13; print "Copying from %s to %s" % (from_file, to_file)&#13; &#13; # we could do these two on one line too, how?&#13; input = open(from_file)&#13; indata = input.read()&#13; &#13; print "The input file is %d bytes long" % len(indata)&#13; &#13; print "Does the output file exist? %r" % exists(to_file)&#13; print "Ready, hit RETURN to continue, CTRL-C to abort."&#13; raw_input()&#13; &#13; output = open(to_file, 'w')&#13; output.write(indata)&#13; &#13; print "Alright, all done."&#13; &#13; output.close()&#13; input.close()&#13; </pre> </div> </td> </tr></tbody></table> 你应该很快注意到了我们 import 了又一个很好用的命令 exists。这个命令将文件名字符串作为参数,如果文件存在的话,它将返回 True,否则将返回 False。在本书的下半部分,我们将使用这个函数做很多的事情,不过现在你应该学会怎样通过 import 调用它。 通过使用 import ,你可以在自己代码中直接使用其他更厉害的(通常是这样,不过也不 尽然)程序员写的大量免费代码,这样你就不需要重写一遍了。 ### 你应该看到的结果 和你前面写的脚本一样,运行该脚本需要两个参数,一个是待拷贝的文件,一个是要拷贝至的文件。如果我们使用以前的 test.txt 我们将看到如下的结果: ~~~ $ python ex17.py test.txt copied.txt Copying from test.txt to copied.txt The input file is 81 bytes long Does the output file exist? False Ready, hit RETURN to continue, CTRL-C to abort. Alright, all done. $ cat copied.txt To all the people out there. I say I don't like my hair. I need to shave it off. $ ~~~ 该命令对于任何文件都应该是有效的。试试操作一些别的文件看看结果。不过小心别把你的重要文件给弄坏了。 Warning 你看到我用 cat 这个命令了吧?它只能在 Linux 和 OSX 下面使用,使用 Windows 的就只好跟你说声抱歉了。 ### 加分习题 1. 再多读读和 import 相关的材料,将 python 运行起来,试试这一条命令。试着看看自己能不能摸出点门道,当然了,即使弄不明白也没关系。 1. 这个脚本 *实在是* 有点烦人。没必要在拷贝之前问一遍把,没必要在屏幕上输出那么多东西。试着删掉脚本的一些功能,让它使用起来更加友好。 1. 看看你能把这个脚本改多短,我可以把它写成一行。 1. 我使用了一个叫 cat 的东西,这个古老的命令的用处是将两个文件“连接(con*cat*enate)”到一起,不过实际上它最大的用途是打印文件内容到屏幕上。你可以通过 mancat 命令了解到更多信息。 1. 使用 Windows 的同学,你们可以给自己找一个 cat 的替代品。关于 man 的东西就别想太多了,Windows 下没这个命令。 1. 找出为什么你需要在代码中写 output.close() 。