一、文件读写
f = open("datafile.txt","w")
f.write("This is my phone book")
f.close()
f = open("datafile.txt","r")
fContent = f.readline()
print(fContent)
f.close()
"""
权限:
r read
w write
x exclusive 独占
a append 如果该文件存在,不清空该文件,在文件末尾添加内容
+ r+,w+ a+ 既可以读又可以写
"""
文件头偏移(类似word中的 光标)
import io
f = open("randomAccess.txt","w+")
sText = "汉"+"".join(str(x) for x in range(30))
f.write(sText)
f.seek(6)
f.write("OFFSET")
f.close()
标准输入、输出、错误流重定向
import sys
fIn = open("input.txt","w")
fIn.write("mail\n")
fIn.write("lee\n")
fIn.close()
fIn = open("input.txt","r")
sys.stdin = fIn
fOut = open("outopen.txt","w")
sys.stdout = fOut
sname = input("What is your name?")
print("Hello!{}".format(sname))
fError = open("Error.txt","w")
sys.stderr = fError
fOut.close()
fIn.close()
fError.close()
结构化文本存储数据
import configparser
class Score :
def __init__(self,lessonname, grade):
self.sLessonName = lessonname
self.iGrade = grade
class Student :
def __init__(self,No = "", name = "", age = 0) :
self.sNo = No
self.sName = name
self.iAge = age
self.Scores =[]
def addSore(self, lessonName,grade):
self.Scores.append(Score(lessonName,grade))
def save(self, filename):
data = configparser.ConfigParser()
sSection = "Basic Information"
data[sSection] = {}
data[sSection]["sNo"] = self.sNo
data[sSection]["sName"] = self.sName
data[sSection]["iAge"] = str(self.iAge)
sSection = "Lesson and socre"
data[sSection] = {}
data[sSection]["scores.size"] = str(len(self.Scores))
for idx,v in enumerate(self.Scores):
data[sSection]["sLessonName[{}]".format(idx)] = v.sLessonName
data[sSection]["sGrade[{}]".format(idx)] = str(v.iGrade)
with open(filename ,"w") as file:
data.write(file)
def load(self,filename):
data = configparser.ConfigParser()
data.read(filename)
sSection = "Basic Information"
self.sNo = data[sSection]["sNo"]
self.sName = data[sSection]["sName"]
self.iAge = int(data[sSection]["iAge"])
sSection = "Lesson and socre"
isize = int(data[sSection].get("scores.size",0))
for idx in range(isize):
sLessonName = data[sSection]["sLessonName[{}]".format(idx)]
iGrade = float(data[sSection]["sGrade[{}]".format(idx)])
self.Scores.append(Score(sLessonName,iGrade))
t = Student()
t.load("dara.ini")
print(t.sName, t.sNo, t.iAge)
for x in t.Scores:
print(x.sLessonName, x.iGrade)
json 文件
import json
dora = {"name":"Dora CHEN", "no":"2018173", "age":26,"married":False,
"scores":[{"C++":76},{"Data Structure":99.5},{"Home Econoics":62}]}
print(json.dumps(dora))
with open("dora.json","w") as f:
json.dump(dora,f)
with open("dora.json") as f:
doraLoaded = json.load(f)
for key,value in doraLoaded.items():
print(key,":", value)
打包和解包二进制文件
import struct
filename = "ergcurve.dat"
f = open(filename,"rb")
rawData = f.read()
f.close()
iSampleCount = len(rawData)//4
curveData = []
for i in range(iSampleCount):
fValue,= struct.unpack("<f",rawData[4*i:4*(i+1)])
curveData.append(fValue)
import matplotlib.pyplot as plt
plt.plot(curveData)
plt.show()
filname = "ergcurve2.dat"
f = open(filename,"wb")
for x in curveData:
data = struct.pack("<f", x)
f.write(data)
f.close()
管道、异常的捕捉
import warnings
def divide(a, b):
fResult= a/b
if fResult < 0.00001:
warnings.warn("The result is close to zero")
return fResult
while True :
sFirstNumber = input("plesea input first number:")
sSecondNumber = input("plesea input second number:")
if sFirstNumber == "q" or sSecondNumber == "q":
break
try:
iFirst = int(sFirstNumber)
iSecond = int(sSecondNumber)
fResult = divide(iFirst, iSecond)
except(ZeroDivisionError) as e:
print("error type is :",e)
except(ValueError,TypeError) as e:
print("error type is :",e)
except(Exception) as e:
print("An exception found")
raise
else:
print("{}/{}={}".format(iFirst, iSecond, fResult))
finally:
print("finally will be excuted wahtever hanpped")
错误的日志文件
import sys,traceback
from datetime import datetime
fError = open("except_error.log", 'a')
def UserExceptHook(tp, val, tb):
traceList = traceback.format_tb(tb)
html = repr(tp) + "\n"
html += (repr(val) + "\n")
for line in traceList:
html += (line + "\n")
print(html, file=sys.stderr)
print(datetime.now(), file=fError)
print(html, file=fError)
fError.close()
def main():
sFirst = input("First number:")
sSecond = input("Second number:")
try:
fResult = int(sFirst) / int(sSecond)
except Exception:
print("发现异常,但我不处理,抛出去.")
raise
else:
print( sFirst, "/", sSecond, "=", fResult)
sys.excepthook = UserExceptHook
main()
fError.close()
二、单元的测试模块,测试用例
import unittest
class TestisPrime(unittest.TestCase):
def testisPrime(self):
self.assertEqual(isPrime(2), True, "素数判断错误" )
self.assertEqual(isPrime(1), False, "1不是素数,素数判断错误" )
self.assertEqual(isPrime(12),False, "素数判断错误" )
self.assertEqual(isPrime(7), True, "素数判断错误" )
self.assertEqual(isPrime(-8), False, "负数不是素数,素数判断错误" )
self.assertEqual(isPrime(0), False, "负数不是素数,素数判断错误" )
def isPrime (n):
if n < 2:
pass
else:
for x in range(n//2, 2):
if (n % x) ==0:
return False
return True
if __name__ == "__main__":
unittest.main()
三、模块的建立和使用
已有模块的信息获取
import os
print(os.__all__)
print(os.__file__)
help(os)
模块的建立
import configparser
import os
class Stat:
sFileName = os.path.expanduser("~") +os.sep +"stat.dat"
def __init__(self) -> None:
self.__load()
def __load(self):
data = configparser.ConfigParser()
data.read(Stat.sFileName)
if "Stats" not in data.keys():
data["Stats"] = {}
self.iCount = 0
self.iTotal = int(data["Stats"].get("iTotal",0))
def __save(self):
data = configparser.ConfigParser()
data["Stats"] = {}
data["Stats"]["iCOunt"] = str(self.iCount)
data["Stats"]["iTotal"] = str(self.iTotal)
with open(stat.sFileName,"w") as f:
data.write(f)
def add(self):
self.iCount += 1
self.iTotal += 1
self.__save()
print(__name__, "Module imported")
stat = Stat()
print()
模块建立后,可以用import 模块名,使用建立的模块
import Stat
for x in range(14):
Stat.stat.add()
print(Stat.stat.iCount, Stat.stat.iTotal)
|