Python学习笔记五(函数、文件操作、异常处理)
一、函数
1、函数的定义
#函数的定义
def printinfo():
print("-" * 30)
print("人生苦短,我用python")
print("-" * 30)
#函数的调用
printinfo()
运行结果:
------------------------------
人生苦短,我用python
------------------------------
2、带多个参数及返回值的函数
多个返回值用逗号隔开
需要使用多个返回值来保存内容
def divde(a,b):
shang = a//b
yushu = a%b
return shang,yushu
sh,yu = divde(5,2)
print("商:%d,余数:%d"%(sh,yu))
运行结果:
商:2,余数:1
3、全局变量和局部变量
global为设置全局变量(想要在函数中设置全局变量时使用)
二、文件操作
对文件的常用操作:重点记忆“r”、“w”、“rb”、“wb”

1、写文件
#打开文件,w模式(写模式),如果文件不存在,就新建,新建文件默认在该py文件目录下
f = open("test.txt","w")
f.write("hello world,i am here!") #将字符串写入文件中
f.close() #关闭文件
2、读文件
(1)read方法
#read方法,读取指定的字符,开始时定位在文件头部,每执行一次向后移动指定字符数
f = open("test.txt","r")
content = f.read(5)
print(content)
content = f.read(10)
print(content)
f.close()
运行结果:(空格也算一个字符)
hello
world,i a
(2)readlines方法
【文件test.txt内有两行字符,均为: hello world,i am here!】
f = open("test.txt","r")
content = f.readlines() #一次性读取全部文件为列表,每行的内容归为一个字符串元素
print(content)
i = 1
for temp in content:
print("%d : %s"%(i,temp),end="")
i += 1
f.close()
运行结果:
['hello world,i am here!\n', 'hello world,i am here!']
1 : hello world,i am here!
2 : hello world,i am here!
(3)readline方法
【文件test.txt内有两行字符,分别为: hello world,i am here!-1以及hello world,i am here!-2】
f = open("test.txt","r")
content = f.readline()
print("1:%s"%content,end="")
content = f.readline()
print("2:%s"%content,end="")
f.close()
运行结果:
1:hello world,i am here!-1
2:hello world,i am here!-2
3、有时候需要对文件进行重命名、删除等相关操作,都可以引进OS模块
import os
os.rename("text.txt","text1.txt") #将text.txt文件重命名为text1.txt
删除文件(remove)、创建文件夹(mkdir)、获取当前路径(getcwd)、改变默认路径(chdir)、获取目录列表(listdir)、删除文件夹(rmdir)等
三、异常处理
#捕获所有异常
try:
f = open("test1.txt", "r")
except Exception as result:
print("发生错误了:",result)
所有的异常都可以用Exception来捕获,其中result只是一个变量名
运行结果:
发生错误了: [Errno 2] No such file or directory: 'test1.txt'
** try...finally
写古诗、把一个文件的内容复制到另一个文件
【encoding定为utf-8确定文件内容为中文,而不是乱码】
【需要先以“r”方式打开,才能读取文件内容,不然会报错】
#写古诗
f = open("gushi.txt","w",encoding="utf-8")
f.write("静夜思\n李白\n床前明月光,疑是地上霜。\n举头望明月,低头思故乡。")
f = open("gushi.txt","r",encoding="utf-8")
content = f.readlines()
print(content)
f.close()
运行结果:
['静夜思\n', '李白\n', '床前明月光,疑是地上霜。\n', '举头望明月,低头思故乡。']
#复制文件内容
f = open("gushi.txt","r",encoding="utf-8")
content = f.readlines()
h = open("copy.txt","w",encoding="utf-8")
for temp in content:
h.write(temp)
h = open("copy.txt","r",encoding="utf-8")
content = h.readlines()
print(content)
h.close()
运行结果:
['静夜思\n', '李白\n', '床前明月光,疑是地上霜。\n', '举头望明月,低头思故乡。']
更多推荐



所有评论(0)