Python 基础练习03

来源:互联网 发布:免费域名注册申请 编辑:程序博客网 时间:2024/06/05 15:45
#!/usr/local/bin/python#encoding:utf-8'''文件的模式如果想修改文件的内容,需要提供文件的模式- 读(默认值):r- 写:w- 追加:a1、open默认以读模式打开,并且我们打开的,一定是个存在的文件,否则会报错。而这个文件,可以是相对路径,也可以是绝对路径2、但是我们以写模式打开的时候,如果这个文件不存在,则创建,这里面不会报错''''''读f = open('demo.txt','r')print f.read(4)print f.read(2)print f.read()f.close()需要注意3、文件指针的问题''''''读一行,也可以传入参数,限制个数f = open('demo.txt')print f.readline()f = open('demo.txt')print f.readlines()''''''写f = open('demo.txt','w')f.write('hello\n')f.write('world')f.close()''''''写一行writelinesf = open('demo.txt','w')f.writelines(['hello\n','wrold'])f.close''''''追加模式用a模式,练习一下之前的write例子,感受一下区别f = open('demo.txt','a')f.write('hello\n')f.write('world')f.close()'''''''''# f = open('helloworld.txt','r')# while True:#     char = f.read(1)#     if char:#         print char#     else:#         break# f.close()'''小练习读取一个文件,请输出其内容去除该文本的换行请替换其中的字符"Chris"为"Alvin"复制这个文件,把第三行内容换为'Sherman'插入一行 "Sherman is best!"Hello World! Welcome to DC-SeismicI am Chris.Luke is one of my partner.I work in Seismic.Seismic is the best Team in DC.'''# # read# f = open('file.txt')# for i in f.readlines():#     print i# f.close()# #strip space# f = open('file.txt')# l1 = []# l2 = f.readlines()# for i in l2:#     l1.append(i.strip('\n'))# f.close()# l4 = []# for i in l1:#     l3 = i.split(' ')#     for k,v in enumerate(l3):#         if v == 'reboot':#             l3[k] = 'hello'#     l4.append(''.join(l3))# f = open('file.txt','w')# f.writelines(l4)# f.close()# #change row2 wd# l2[1] = 'wd\n'# f = open('file2.txt','w')# f.writelines(l2)# f.write('i am good\n')# f.close()'''小练习tem.txt存储着日期和时间的数据,求最高温度和平均温度date    tem7.20    257.21    25.57.22    247.23    267.24    287.25    27'''# f = open('tem.txt')# l1 = f.readlines()# f.close()# d = {}# for i in l1[1:]:#     l2 = i.split(' ')#     d[l2[0]] = l2[3].strip('\n')# l3 = []# for v in d.values():#     l3.append(v)# print 'the top: %s' % max(l3)## c = 0# for i in l3:#     c = c + float(i)# avg = c/len(l3)# print 'the avg: %f' % avg'''错误处理代码出现异常是很常见的,比如open一个不存在的文件我们需要控制异常,如果出错了,不能让程序崩溃我们可以手动抛出异常,定义自己的错误类型''''''捕捉异常try ... except ... else ... finallytry:    可能出错的代码except:    如果出错else:    如果不出错finally:    出不出错都执行''''''try:    f = open('xx.txt')except:    print 'file not exist'else:    print 'file exist'finally:    print 'always''''

0 0
原创粉丝点击