《笨办法学Python》 第17课手记
2016-01-19 22:16
856 查看
《笨办法学Python》 第17课手记
本节内容是前几节内容的复习和综合,此外引入了exists函数。原代码如下:
from sys import argv from os.path import exists script, from_file, to_file = argv print "Copying from %s to %s" %(from_file, to_file) #we could do these two on the line too, how? in_file = open(from_file) indata = in_file.read() print "The input file is %d bytes long" % len(indata) print "Does the output file exist? %r" % exists(to_file) print "Ready, hit RETURN to comtinue, CTRL-C to abort." raw_input() out_file = open(to_file, 'w') out_file.write(indata) print "Alright,all done." out_file.close() in_file.close()
结果如下:
exists函数是检查括号内字符串所代表的文件名的文件是否存在,存在返回True,不存在返回False。
请注意,这里作者所说的复制并不是使用了一个专门用来复制字符的函数,而是采用了变量赋值的方式实现复制。
in_file = open(from_file) #将open函数得到的结果(是一个文件,而不是文件的内容)赋值给in_file。 indata = in_file.read() #使用read函数读取文件内容,并将文件内容赋值给indata。
剩下的在作者的常见问题解答中有提到,这里不再赘述。
本节课涉及的内容
cat 在C语言字符串操作里strcat也表示字符串连接的意思str(char dst, cahr src)中,如果dst是空的,也就是将src复制到dst的意思。至于windows中cat的替代品。显示的话用的是Type,复制的话是copy。
len(),该函数返回的长度是指字节数。
indata = open(from_file).read(),是一种简化的写法,如果你想化简上面的代码,可以尝试使用这种形式来写。
下面是可能的一种简写方法,一行写出来我做不到,除非使用cat。
from sys import argv script, from_file, to_file = argv to_file = open(to_file, 'w') to_file.write( open(from_file).read())
相关文章推荐
- Python的排序:关于sort()与sorted()
- 函数:Python的乐高积木
- 我的Python成长之路---第三天---Python基础(13)---2016年1月16日(雾霾)
- 我的Python成长之路---第三天---Python基础(12)---2016年1月16日(雾霾)
- 我的Python成长之路---第三天---Python基础(11)---2016年1月16日(雾霾)
- python核心编程-使用线程锁
- Python 5.4 定制类
- python核心编程-线程
- Python 生成的页面中文乱码问题
- python基础之字典
- python更改或者查看当前工作目录
- 使用PYTHON解析Wireshark的PCAP文件
- 八大排序算法的Python实现
- 八大排序算法的Python实现
- CAS单点登录python客户端分析
- 使用PYTHONPATH来使用其他版本的Django来启动
- Python3.4 IP查询(api)
- python 中 五种字典(dict)的遍历方法,实验法比较性能。
- python random.shuffle(随机打乱列表等) 和 random.random
- python实现一个朴素贝叶斯分类器