一、函数
def test(): #函数的定义
return 111
a = test() #函数的调用
print(a) #111
def jsq(num1,num2):
print(num1 * num2)
jsq(1,2) #2
def value(num1,num2):
return num1,num2
value1,value2 = value(2,3)
print(value1,value2) #2 3 返回多个值,需要多个变量接收
def tset1(num1,num2,num3):
return num1+num2+num3
print(tset1(10,2,2) / 3)
二、文件
# 打开文件, w模式(写模式):文件没有的话会在当前目录创建了、有的话就会覆盖 , r 只读,没有文件的话就会报错 ,rb以二进制方式打开文件
f = open("test.txt",'w')
f.write('hello,word!')
f.close()
f = open('test.txt','r')
content = f.read(5)
print(content) # hello 读取文件的内容 read(),读取指定的字符,开始时定位在文件头部,没执行一次向后移动指定字符数
content = f.read(5)
print(content) # ,word
f.close()
f = open('test.txt','r')
content = f.readlines()
print(content) #['hello,word 1!\n', 'hello,word 2!'] readlines()将所有的数据全部读取出来,每一列就是一个元素
i = 1
for item in content:
print('第%d列,%s'%(i,item)) # 第1列,hello,word 1! 第2列,hello,word 2!
i += 1
f.close()
f = open('test.txt', 'r')
content = f.readline()
print(content) # hello,word 1! readline() 读取固定的第一行
f.close()
import os
os.rename('test.txt','text.txt') # 修改文件名
import os
os.remove('text.txt') # 删除文件
三、异常处理
try:
print('--------1---------')
f = open('test.txt', 'r')
print('--------2---------')
except IOError: # 文件捕获错误,属于IO异常
print('出错了')
try:
print(num)
except NameError: # 异常类型想要被捕获,需要一致 未定义的变量
print('出错了')
try:
f = open('test.txt', 'r')
print(num)
except (NameError,IOError): # 将所有的可能产生的异常,全部写在括号里
print('出错了')
'''
获取错误描述 result
'''
try:
f = open('test.txt', 'r')
print(num)
except (IOError,NameError) as result:
print(result) #No such file or directory: 'test.txt'
'''
监听所有错误 Exception
'''
try:
print(num)
except Exception as result:
print(result) #name 'num' is not defined
'''
try...finally 和嵌套 #finally不管程序报不报错都会执行关闭文件的时候可以操作
'''
try:
test = open('gushi.txt','w')
test.write('床前明月光\n疑是地上霜\n举头望明月\n低头思故乡')
test.close()
except Exception as result:
pass
'''
应用文件操作的相关知识,通过Python新建一个文件gushi.txt,选择一首古诗写入文件
另外写一个函数,读取指定文件gushi.txt,将内容复制到copy.txt中,并在控制台输出'复制完毕'
提示:分别定义两个函数,完成读文件和写文件的操作
尽可能完善代码,添加异常处理
'''
def write():
f = open('gushi.txt','r')
gushi = f.readlines()
if len(gushi) > 0:
copy = open('copy.txt', 'w')
for item in gushi:
read(item)
print('复制完毕')
copy.close()
def read(item):
try:
copy = open('copy.txt', 'a') # 往现有文件屁股后面加文件
copy.write(item)
copy.close()
except Exception as result:
pass
write()
新手学习请勿喷!
欢迎各位小伙伴来我的QQ交流群一起学习 :842167453