《笨办法学Python》 第17课手记

时间:2022-04-26
本文章向大家介绍《笨办法学Python》 第17课手记,主要内容包括《笨办法学Python》 第17课手记、本节课涉及的内容、基本概念、基础应用、原理机制和需要注意的事项等,并结合实例形式分析了其使用技巧,希望通过本文能帮助到大家理解应用这部分内容。

《笨办法学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())