Learn Python The Hard Way学习(17) - 更多的文件操作


让我们写一个复制文件的python脚本,能让我们对文件操作有更多的了解。
[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. 看看你能把程序写得多短。 www.2cto.com
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()?
为了释放系统资源。

 作者:lixiang0522

相关内容

    暂无相关文章

评论关闭