- 浏览: 2486466 次
- 性别:
- 来自: 成都
文章分类
最新评论
-
nation:
你好,在部署Mesos+Spark的运行环境时,出现一个现象, ...
Spark(4)Deal with Mesos -
sillycat:
AMAZON Relatedhttps://www.godad ...
AMAZON API Gateway(2)Client Side SSL with NGINX -
sillycat:
sudo usermod -aG docker ec2-use ...
Docker and VirtualBox(1)Set up Shared Disk for Virtual Box -
sillycat:
Every Half an Hour30 * * * * /u ...
Build Home NAS(3)Data Redundancy -
sillycat:
3 List the Cron Job I Have>c ...
Build Home NAS(3)Data Redundancy
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:
参考书籍 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:
发表评论
-
NodeJS12 and Zlib
2020-04-01 07:44 430NodeJS12 and Zlib It works as ... -
Traefik 2020(1)Introduction and Installation
2020-03-29 13:52 291Traefik 2020(1)Introduction and ... -
Private Registry 2020(1)No auth in registry Nginx AUTH for UI
2020-03-18 00:56 373Private Registry 2020(1)No auth ... -
Buffer in NodeJS 12 and NodeJS 8
2020-02-25 06:43 334Buffer in NodeJS 12 and NodeJS ... -
NodeJS ENV Similar to JENV and PyENV
2020-02-25 05:14 415NodeJS ENV Similar to JENV and ... -
Prometheus HA 2020(3)AlertManager Cluster
2020-02-24 01:47 359Prometheus HA 2020(3)AlertManag ... -
Serverless with NodeJS and TencentCloud 2020(5)CRON and Settings
2020-02-24 01:46 291Serverless with NodeJS and Tenc ... -
GraphQL 2019(3)Connect to MySQL
2020-02-24 01:48 207GraphQL 2019(3)Connect to MySQL ... -
GraphQL 2019(2)GraphQL and Deploy to Tencent Cloud
2020-02-24 01:48 390GraphQL 2019(2)GraphQL and Depl ... -
GraphQL 2019(1)Apollo Basic
2020-02-19 01:36 274GraphQL 2019(1)Apollo Basic Cl ... -
Serverless with NodeJS and TencentCloud 2020(4)Multiple Handlers and Running wit
2020-02-19 01:19 263Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(3)Build Tree and Traverse Tree
2020-02-19 01:19 259Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(2)Trigger SCF in SCF
2020-02-19 01:18 250Serverless with NodeJS and Tenc ... -
Serverless with NodeJS and TencentCloud 2020(1)Running with Component
2020-02-19 01:17 234Serverless with NodeJS and Tenc ... -
NodeJS MySQL Library and npmjs
2020-02-07 06:21 233NodeJS MySQL Library and npmjs ... -
Python Library 2019(1)requests and aiohttp
2019-12-18 01:12 225Python Library 2019(1)requests ... -
NodeJS Installation 2019
2019-10-20 02:57 517NodeJS Installation 2019 Insta ... -
Monitor Tool 2019(2)Monit on Multiple Instances and Email Alerts
2019-10-18 10:57 229Monitor Tool 2019(2)Monit on Mu ... -
Sqlite Database 2019(1)Sqlite3 Installation and Docker phpsqliteadmin
2019-09-05 11:24 319Sqlite Database 2019(1)Sqlite3 ... -
Supervisor 2019(2)Ubuntu and Multiple Services
2019-08-19 10:53 320Supervisor 2019(2)Ubuntu and Mu ...
相关推荐
文件处理和异常处理【Python一周入门教程7】
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
【python入门必背】python入门基础知识点合集、python基础知识背记手册 主要内容概要: 第1章 走进 Python. 第2章 Python语言基础 第3章 运算符与表达式 第4章 流程控制语句 第5章 列表与元组 第6章 字典与集合 第...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
python文件存取和异常处理_python基础,快速入门.pptx, python对文件的处理,包括文件读取,文件写入,python异常的处理,自定义异常,常见异常汇总等
《python入门经典:以解决计算问题为导向的python编程实践》不仅适合入门级的python程序员系统学习,也适合作为高等院校计算机和非计算机专业的程序设计课程教材。 《Python入门经典:以解决计算问题为导向的Python...
全书分两部分:第一部分介绍用Python 编程所必须了解的基本概念,包括matplotlib、NumPy 和Pygal 等强大的Python 库和工具介绍,以及列表、字典、if 语句、类、文件与异常、代码测试等内容;第二部分将理论付诸实践...
课程的性质和任务 是面向信息技术及其计算机相关专业的一门专业基础课,涉及Python语法、数据类 型、函数、文件操作、异常、模块、面向对象等内容。通过本课程的学习,学生能够掌 握Python开发的基础知识,可以独立...
Python入门教程是一套针对初学者的编程教材,旨在帮助学习者从零基础开始学习和掌握Python编程语言。 以下是Python入门教程可能包含的一些主要内容: 环境搭建:介绍如何安装Python解释器和相关开发环境,包括常用...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
Python基础入门教程 Python语言编程导论06 第六章 数据结构 (共114页).ppt Python基础入门教程 Python语言编程导论07 第七章 文件处理 (共55页).ppt Python基础入门教程 Python语言编程导论08 第八章 面向对象...
Python基础入门教程 Python语言编程导论06 第六章 数据结构 (共114页).ppt Python基础入门教程 Python语言编程导论07 第七章 文件处理 (共55页).ppt Python基础入门教程 Python语言编程导论08 第八章 面向对象...
Python基础入门教程 Python语言编程导论06 第六章 数据结构 (共114页).ppt Python基础入门教程 Python语言编程导论07 第七章 文件处理 (共55页).ppt Python基础入门教程 Python语言编程导论08 第八章 面向对象...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
Python从入门到精通 第12章 异常处理及程序调试.ppt Python从入门到精通 第13章 文件及目录操作.ppt Python从入门到精通 第14章 操作数据库.ppt Python从入门到精通 第15章 GUI界面编程.pptx Python从入门到精通 第...
Python基础入门教程 Python语言编程导论06 第六章 数据结构 (共114页).ppt Python基础入门教程 Python语言编程导论07 第七章 文件处理 (共55页).ppt Python基础入门教程 Python语言编程导论08 第八章 面向对象...
Python基础入门教程 Python语言编程导论06 第六章 数据结构 (共114页).ppt Python基础入门教程 Python语言编程导论07 第七章 文件处理 (共55页).ppt Python基础入门教程 Python语言编程导论08 第八章 面向对象...