python练习题及实现--文件处理、date日期

练习题作者:Vamei 出处:http://www.cnblogs.com/vamei
 
【实现】
 
#!/usr/bin/python
# -*-coding:utf-8-*-
 
#-------计算日期差
'''
import datetime
from datetime import date
d1=date(2008,1,1)
d2=date(2008,10,1)
t=abs(d2-d1)
n=t.days+1
print n
 
#----判断2008是否为闰年
def leapyear(year):  #判断year是否为闰年,ture为闰年,false为非闰年
    years=year*1
    if(years%100): ##不能整除100进入条件语句
        return not(years%4) #能整除4返回ture,不能整除4,返回false
    else:        ##能整除100
        return not(years%400)  #能整除4返回ture,不能整除4,返回false
 
 
#a=leapyear(2000)
#print(leapyear(2000),leapyear(2008),leapyear(1900),leapyear(1833))
'''
##----文件处理
# 主要用的list的index和读取字符串split/strip及index读取;另外可以使用zip将名字、年龄、分数组成元祖列表然后使用for(a,b)in s.numerate 读取满足条件类型的index再读取需要输出类型
#因为需要更正错误的地方所有需要打开两次该文件,一份用来读取,一份用来重写,故需要注意不需要更正的行+跳过的地方写入原内容
import os,sys
#import linecache
reload(sys)
sys.setdefaultencoding('utf-8')
 
filepath='E:\记录.txt'.decode('utf-8').encode('GB2312')  ##打开windows中文路径解析
 
with open(filepath, 'r+') as f1:
    f1.seek(0)
    l = f1.readlines()
 
with open(filepath, 'w+') as f:
    sum=0
    n=0
    a=0
    f.seek(0)  ##读取文件时光标位置重新回到头部,否则容易读到空
    print 'the all contents is:\n',f.read()
    f.seek(0)
    for line in l:
        if (line.isspace()):  ##处理文件为空行的数据
            line=line
            f.write(line)
            continue
        if (line[0]=='#'):  ##忽略带#开头的行   或者使用 if(not line.startswith('#'))
            line=line
            f.write(line)
            continue
        a=a+1
        l1=line.split(',')
        l1[2] = l1[2].strip('\n')#去除尾部的\n
 
        if (l1[2]*1<60):
            print 'whose score is lower than 60:',l1[0]
 
 
        if(l1[0][0]=='L'):
            print 'whose name begins with L:', l1[0]
 
        sum = sum + int(l1[2])
 
        if(not l1[0].istitle()):
            n=n+1
            line=line.capitalize()
        f.write(line)
 
print'the totalscore is', sum
print'the name in the file is all title:',(n==0)
 

猜你喜欢

转载自www.cnblogs.com/suyuloying/p/9262487.html