笨方法学Python(2),,习题 15: 读取文


习题 15: 读取文件

习题 16: 读写文件

‘w‘ 是什么意思?
它只是一个特殊字符串,用来表示文件的访问模式。如果你用了 ‘w‘ 那么你的文件就是写入(write)模式。除了 ‘w‘ 以外,我们还有 ‘r‘ 表示读取(read), ‘a‘ 表示追加(append)。

最重要的是 + 修饰符,写法就是 ‘w+‘, ‘r+‘, ‘a+‘ ——这样的话文件将以同时读写的方式打
开,而对于文件位置的使用也有些不同。
如果只写 open(filename) 那就使用 ‘r‘ 模式打开的吗?
是的,这是 open() 函数的默认工作方式(无法修改)。

习题 17: 更多文件操作

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)

in_file = open(from_file)
indata = in_file.read()

print "The input file is %d bytes long" % len(indata)

print "Does the output file exists? %r" % exists(to_file)
print "Ready, hit RETURN to continue,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()
#另一种写法(只需一行):
from sys import argv

script,from_file,to_file = argv

open(to_file,‘w‘).write(open(from_file).read())
习题 18: 命名,变量,代码,函数

函数名称有什么规则?
和变量名一样,只要以字母数字以及下划线组成,而且不是数字开始,就可以了。
*args 的 * 是什么意思?
它的功能是告诉 python 让它把函数的所有参数都接受进来,然后放到名字叫 args 的列表中去。
和你一直在用的 argv 差不多,只不过前者是用在函数上面。没什么特殊情况,我们一般不会经
常用到这个东西。

习题 19: 函数和变量
def print_two(*args):
arg1,arg2 = args
print "arg1: %r, arg2: %r" % (arg1, arg2)

def print_two_again(arg1, arg2):
print "arg1: %r, arg2: %r" % (arg1, arg2)

笨方法学Python(2)

相关内容

    暂无相关文章

评论关闭