您的位置:首页 > 编程语言 > Python开发

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

2012-06-19 16:35 781 查看
让我们写一个复制文件的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()?
为了释放系统资源。
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: