Learn Python The Hard Way学习(17) - 更多的文件操作
2012-06-19 16:35
781 查看
让我们写一个复制文件的python脚本,能让我们对文件操作有更多的了解。
你会很快发现我们导入了新的方法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()?
为了释放系统资源。
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学习(24) - 更多的练习
- Learn Python The Hard Way学习(25) - 甚至更多的练习
- Learn Python The Hard Way学习(38) - 列表操作
- Learn Python The Hard Way学习(7) - 更多的打印
- Learn Python The Hard Way学习(20) - 函数和文件
- Learn Python The Hard Way学习(15) - 读取文件
- Learn Python The Hard Way学习(16) - 读写文件
- Learn Python The Hard Way学习(16) - 读写文件
- Learn Python The Hard Way学习(5) - 更多的变量和打印
- 【Python】Learn Python the hard way, ex39 字典操作
- Learn Python The Hard Way学习(36) - 设计和调试
- Learn Python The Hard Way学习(40) - 模块,类和对象
- 【Python】Learn Python the hard way, ex17 文件复制
- 函数与文件-习题20--learn python the hard way
- Learn Python The Hard Way学习(48) - 更高级的用户输入
- Learn Python The Hard Way学习(50) - 你的第一个网站
- Learn Python The Hard Way学习(29) - 什么是If
- 学习learn python the hard way习题46, ImportError问题
- 读写文件,python. learn python the hard way
- Learn Python The Hard Way学习(37) - 复习