让我们写一个复制文件的python脚本,能让我们对文件操作有更多的了解。
from sys import argv
from os.path import exists
script, from_file, to_file = argv
print "Copy from %s to %s" % (from_file, to_file)
# we could do these two on one line too, how?
input = open(from_file)
indata = input.read()
print "The input file is %d bytes long" % len(indata)
print "Dose the output file exist? %r" % exists(to_file)
print "Ready, hit RETURN to continue, CTRL-C to abort."
raw_input()
output = open(to_file, 'w')
output.write(indata)
print "Alright, all done."
output.close()
input.close()
你会很快发现我们导入了新的方法exists。如果文件存在的话会返回True,不存在返回False,这个方法很常用,所以记住怎么导入它。
利用import可以导入很多别人写好的方法。
运行结果
root@he-desktop:~/mystuff# python ex17.py test.txt copied.txt
Copy from test.txt to copied.txt
The input file is 6 bytes long
Dose the output file exist? False
Ready, hit RETURN to continue, CTRL-C to abort.
Alright, all done.
对任何文件都应该有效,试试其他文件,不过要注意别吧重要的文件弄坏了。
提示:linux下可以使用cat copied.txt查看文件。
加分练习
1. 去看一些import的描述,启动python,尝试练习使用一下这个方法。
应该避免使用from ... import ... ,容易和当前代码的变量产生冲突。
2. 这个练习的脚步有点烦人,没必要在复制前询问吧,尝试去掉不必要的输出。
3. 看看你能把程序写得多短。
from sys import argv;open(argv[2], 'w').write(open(argv[1]).read())
4. cat命令的用途是打印文件到屏幕上,使用man cat查看他的用法。
5. windows的用户可以找其他方法代替cat,另外,windows中没有man的用法。
6. 为什么要使用output.close()?
为了释放系统资源。
分享到:
相关推荐
learn-python-the-hard-way中文版,o基础学习python!||随手上传是种美德
Shaw is the author of the popular online books Learn Python the Hard Way, Learn Ruby the Hard Way, and Learn C the Hard Way. He is also the creator of several open source software projects like ...
Learn-Python-3-the-Hard-Way.pdf
Learn Python the Hard Way
Learn Python The Hard Way, 2nd Edition 英文版 属于独家制作 原创 PDF格式的之前一直上传不了,现在终于可以了http://download.csdn.net/source/3501806, 也可以去我的网盘下载 DBank:...
learn python the hard way.
learn python the hard way 实例代码
Learn Python the Hard Way, 3rd Edition
Learn Python the Hard Way 中文三版 Learn Python the Hard Way 中文三版
In Learn Python 3 the Hard Way, Zed Shaw taught you the basics of Programming with Python 3. Now, in Learn More Python 3 the Hard Way, you’ll go far beyond the basics by working through 52 ...
Learn Python The Hard Way(3rd) 英文无水印pdf 第3版 pdf所有页面使用FoxitReader和PDF-XChangeViewer测试都可以打开 本资源转载自网络,如有侵权,请联系上传者或csdn删除 本资源转载自网络,如有侵权,请...
Learn Python 3 The Hard Way . pdf epub azw3 https://learnpythonthehardway.org/python3/ 原始文件是azw3版本,pdf和epub版本是从azw3版本转换生成。 Learn Python 3 the Hard Way now uses Python 3.6. I’ve ...
Learn Python the Hard Way(包括中文和英文),不错的python教程
You Will Learn Python!
learn python 3 the hard way provides an easy step towards complicated programming in python 3.
Learn Python 3 the hard way,笨办法学Python3 。 简介:The fourth edition of Learn Python The Hard Way now uses Python 3.6. I've standardized on this version of Python because it has a new improved ...
Learn Python The Hard Way - 2011.pdf
Learn Python The Hard Way(笨办法学python) 原书代码