码迷,mamicode.com
首页 > 编程语言 > 详细

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

时间:2018-07-04 13:40:23      阅读:173      评论:0      收藏:0      [点我收藏+]

标签:重写   分数   name   arch   false   inf   lower   api   enc   

练习题作者: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)
 

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

标签:重写   分数   name   arch   false   inf   lower   api   enc   

原文地址:https://www.cnblogs.com/suyuloying/p/9262487.html

(0)
(0)
   
举报
评论 一句话评论(0
登录后才能评论!
© 2014 mamicode.com 版权所有  联系我们:gaon5@hotmail.com
迷上了代码!