輸入學生的姓名和成績,打印學生成績信息,判斷成績等級
#!/usr/bin/env python
#coding=utf-8
class Student(object):
def __init__(self,name,score):
self.__name = name
self.__score = score
def print_score(self): //定義打印成績信息函數
print "%s:%s" %(self.__name,self.__score)
def print_grade(self): //判斷成績等級
if self.__score >=90:
print "A"
elif self.__score >=60:
print "B"
else:
print "C"
def get_name(self):
print self.__name
std1 = Student("fentiao",100)
std2 = Student("hello",80)
std1.print_score()
std2.print_score()
std1.print_grade()
std2.print_grade()
#std1._Student__name = "cat"
#std1.get_name()
打印學生std1,std2的成績信息
#!/usr/bin/env python
#coding=utf-8
class Student(object): //聲明student類
def __init__(self,name,score):
self.name = name
self.score = score
def print_score(self): //定義打印成績的函數
print "%s:%s" %(self.name,self.score)
std1 = Student("zhangzhen",01) //給student傳遞兩個參數
std2 = Student("hejie",80)
std1.print_score() //調用print_score()函數
std2.print_score()
統計一個文件中特定字符串的長度
#!/usr/bin/env python
#coding:utf-8
import re
s=raw_input("please input the str:") //輸入要統計的字符串
filename=raw_input("please input the filename:") //輸入要查找的文件
fo =open(filename)
lines=len(fo.readlines()) //統計文件的行數
fo.seek(0,0)
r=r"%s" %s //定義規則
count=0
for i in range(0,lines): //依次遍歷每一行,統計每行的字符串出現個數
l=re.findall(r,fo.readline()) //按照規則匹配查找的字符串
count+=len(l) //統計匹配到的字符串個數,將值累加到count上
print ("the %s has %d in filename" %(s,count))
將file1中的a字符串用b字符串替換,並將替換後的文件重新保存在file2中
#!/usr/bin/env python
#coding=utf-8
import re
file1name=raw_input("please input the file1:")
file2name=raw_input("please input the file2:")
f1=open(file1name,"r") //file1文件,以只讀方式打開
f2=open(file2name,"w") //file2文件,以只寫方式打開
a=raw_input("please input you want to replaced strings:")//輸入要替換的字符串
b=raw_input("please input you exchanged the strings:") //輸入用來替換的字符串
r=re.compile(r"%s"%a) //定義規則匹配a字符串
file1=f1.read() //讀取file1文件
file1=r.sub("%s"%b,file1) //用b字符串替換按照規則匹配的file1中的a字符串
print "%s replaced %s successful"
f2.write(file1)
f2.close() //關閉文件file1,file2
f1.close()
將指定目錄下的文件複製到指定目錄中去
#!/usr/bin/env python
#coding:utf-8
import os
list=[] //空列表,用來保存所要複製的文件的絕對路徑
back=raw_input("please input the filenameback:") //輸入要複製的文件的絕對路徑
list=[back] //將該路徑保存在列表中
des =raw_input("please input the destination:") //輸入文件的目的路徑
desback=raw_input("please input the desback:")
os.mkdir(des+desback) //創建該目的路徑
command="cp %s %s " %(" ".join(list),des+desback) //執行復制命令
if os.system(command)==0: //如果os.system()返回值位0,則表示複製成功
print "cp successful"
else: //否則,操作失敗
print "operator failed"
遍歷目錄,遞歸取出目錄下的所有文件。
#!/usr/bin/env python
#coding:utf-8
import os
def dirlist(path):
allfilename=[]
flist=os.listdir(path)
for filename in flist:
filepath=os.path.join(path,filename)
if os.path.isdir(filepath):
dirlist(filepath)
else:
allfilename.append(filepath)
return allfilename
print dirlist("/a")
print dirlist("/a/c")