python入门(六)文件和异常
参考书籍 python_note_pdq.pdf
9.1 文件的打开和关闭
python2和python3文件的差别比较大,参考了这个BLOG
http://diveintopython3.org/files.html
def copyFile(oldFile, newFile):
f1 = open(oldFile, mode = "r",encoding='utf-8')
f2 = open(newFile, mode = "w",encoding='utf-8')
while 1:
text = f1.read(50)
if text == "":
break
f2.write(text)
f1.close()
f2.close()
return
f_name = "d:/chinese.txt"
#以写的模式打开文件,并自动关闭文件
with open(f_name, mode='w',encoding='utf-8') as f:
f.write("中文测试")
print(f)
#读取文件,read参数数字是读到第几个字符
with open(f_name, encoding='utf-8') as f:
print(f.read(1)," ",f.read())
#拷贝文件
copyFile("d:/chinese.txt","d:/english.txt")
控制体打印信息如下:
<_io.TextIOWrapper name='d:/chinese.txt' encoding='utf-8'>
中 文测试
注意用UTF-8避免乱码,另外copyFile的时候read(50)这个缓冲是固定的,也可以改为参数式的。
9.2 文本文件
#拷贝文件,过滤器中以#打头的行
def filterCopyFile(old, new):
sfile = open(old, mode="r",encoding="utf-8")
dfile = open(new, mode="w",encoding="utf-8")
while 1:
text = sfile.readline()
if text == "":
break
elif text[0] == "#":
continue
else:
dfile.write(text)
sfile.close()
dfile.close()
f_name = "d:/chinese.txt"
with open(f_name, mode='w',encoding='utf-8') as f:
f.write("中文测试\n#Chinese test\n英文测试\n#English test\n")
with open(f_name,mode='r',encoding='utf-8') as f:
#读取文件,readline读取一行
print(f.readline())
#readlines以列表的方式返回
print(f.readlines())
#游标已经到文件末尾,此时调用就会返回空和空列表
print(f.readline(),":",f.readlines())
filterCopyFile(f_name,"d:/filter.txt")
控制台打印信息:
中文测试
['#Chinese test\n', '英文测试\n', '#English test\n']
: []
9.3 写入变量
write的参数是字符串,如果想写入其他类型到文件,就需要用str转化。另外就是使用格式化序列
age = 13
money = 12.34
words = "hello world"
# %d 代表整数,:(让我想到了C
statement = "my age is %d " % age
print(statement)
# %f 代表浮点数
statement = "I have %f ¥" % money
print(statement)
statement = "I wanna to say: %s " % words
print(statement)
statement = "my age is %d,and I have %f ¥,I want to tell you:%s" % (age,money,words)
print(statement)
控制台打印信息:
my age is 13
I have 12.340000 ¥
I wanna to say: hello world
my age is 13,and I have 12.340000 ¥,I want to tell you:hello world
“%”后面的
数字表明数字的位数,如果位数多于数字的实际位数,且该数为正,则在要格式化的数字的前面添加空格;如果该数为负,空格添加在数字的后面;浮点数里面小数点后的表示小数保留位数
print("||","%5d" % 1,"||")
print("||","%-5d" % 1,"||")
print("||","%4.3f" % 1137.9,"||")
#格式化打印姓名
def printSalary(salary):
name = salary.keys()
for n in name:
print("%-12s : %12.2f" % (n,salary[n]))
salary = {'pidaqing':1137.9, 'zhangming':737.3, 'pitianjian':5.0}
printSalary(salary)
控制台打印信息如下:
|| 1 ||
|| 1 ||
|| 1137.900 ||
pitianjian : 5.00
pidaqing : 1137.90
zhangming : 737.30
将类型转为str可以保存,但是数据的类型信息就丢失了,试试其他方式呢。
pickle 版本有出入,参考文档 http://diveintopython3.org/serializing.html
import pickle
with open("d:/chinese.txt",mode="wb") as f :
pickle.dump(100,f)
pickle.dump(123.93, f)
pickle.dump((1,3,"abc"), f)
pickle.dump([1,3,5],f)
with open("d:/chinese.txt",mode="rb") as f:
a1 = pickle.load(f)
print(a1,type(a1))
a1 = pickle.load(f)
print(a1,type(a1))
a1 = pickle.load(f)
print(a1,type(a1))
a1 = pickle.load(f)
print(a1,type(a1))
打印信息如下:
100 <class 'int'>
123.93 <class 'float'>
(1, 3, 'abc') <class 'tuple'>
[1, 3, 5] <class 'list'>
10.1 错误信息
当异常产生时,如果没有代码来处理它,Python对其进行缺省处理,输出一些异常信息并终止程序。
比如a = 20/0,python会报错如下:
ZeroDivisionError: int division or modulo by zero
前面是错误类型,后面是错误信息,python终止运行,如果用try except处理如下:
filename = ''
while 1:
filename = input("input a file name: ")
filename = filename[:len(filename)-1]
if(filename == 'q'):
break
try:
with open(filename,mode="r",encoding="utf-8") as f :
print("opened a file.")
except:
print("there is no file %s in the disk" % filename)
控制台打印信息如下:
input a file name: d:/test.txt
there is no file d:/test.txt in the disk
input a file name: d:/english.txt
opened a file.
input a file name: q
10.2 自定义异常信息
raise定义异常,raise有两个参数,第一个是由我们自己定义的异常类型,第二个是关于
此异常的少量说明信息。这里有些版本冲突,以后再查看吧。
def inputAge():
age = input("input your age:")
age = int(age[:len(age)-1])
if(age < 18 or age >100):
raise OutOfRangeError('out of range')
return age
while 1:
a = inputAge()
if(a == 27):
break
else:
print(a)
控制台打印信息:
input your age:30
30
input your age:11
Traceback (most recent call last):
File "D:\work\easypython\src\com\sillycat\easypython\TestMain.py", line 8, in <module>
a = inputAge()
File "D:\work\easypython\src\com\sillycat\easypython\TestMain.py", line 5, in inputAge
raise OutOfRangeError('out of range')
NameError: global name 'OutOfRangeError' is not defined
10.3 复杂的示例
while 1:
try:
x = int(input("Input a number:"))
y = int(input("Input a number:"))
z = x / y
except ValueError :
print("That is no valid number.")
except ZeroDivisionError :
print("divisor is zero:")
except:
print("Unexpected error.")
raise
else:
print ("There is no error.")
print(x , "/" , y , "=" , x/y)
控制台打印信息:
Input a number:1
Input a number:1
There is no error.
1 / 1 = 1.0
Input a number:1
Input a number:0
divisor is zero:
Input a number:a
That is no valid number.
Input a number: