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

《笨办法学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())
内容来自用户分享和网络整理,不保证内容的准确性,如有侵权内容,可联系管理员处理 点击这里给我发消息
标签: