python:函数、参数传递、递归
- 1、测试写入中文
- 2、测试异常
- 3.csv文件的操作读取和写入
- 4.os模块调用操作系统文件和命令和os.path模块
- 5.递归算法
1、测试写入中文
#1测试写入中文
f=open(r"c:/Users/FYL/Desktop/a.txt","w")
f.write("尚学堂\n百战程序员\n")
f.close()
#使用异常机制管理文件对象的关闭操作
try:
f=open(r"e.txt","w")
strs=["aa","cc","bb"]
f.writelines(strs)
except BaseException as e:
print(e)
finally:
f.close()
# 2.文本文件的读取工作read,readline,readlines
#read
with open("e.txt","r",encoding="utf-8") as f:
str=f.read()
print(str)
with open("e.txt","r",encoding="utf-8") as f:
for a in f:
print(a,end="")
#3.enumerate
a=["我love u","尚学堂\n","百战程序员\n"]
b=enumerate(a)
print(a)
print(list(b))
#4.推导式
with open("e.txt","r",encoding="utf-8") as f:
lines=f.readlines()
lines=[line.rstrip()+" #"+str(index+1)+'\n' for index,line in enumerate(lines)]#推导式生成列表
print(lines)
with open("e.txt","w",encoding="utf-8")as f:
f.writelines(lines)
#5,二进制文本的操作
with open("dog.jpg","rb") as f:
with open("copy_dog.jpg","wb") as w:
for lines in f.readlines():
w.write(lines)
print("图片拷贝完成")
#6.文件对象的常用方法和属性
#seek
with open("e.txt","r",encoding="utf-8") as f:
print("文件名是:{0}".format(f.name))
print(f.tell())#读取指针当前的位置
print("读取的内容:{0}".format(f.readline()))
print(f.tell())
print(f.seek(3))
print("读取的内容:{0}".format(f.readline()))
#7.pickle对象序列化
import pickle
a1="赵薇"
a2=234
a3=[10,20,30]
with open("data.dat","wb") as f:
pickle.dump(a1,f)
pickle.dump(a2,f)
pickle.dump(a3,f)
with open("data.dat","rb") as f:
b1=pickle.load(f)
b2=pickle.load(f)
b3=pickle.load(f)
print(b1)
print(b2)
print(b3)
2、测试异常
#1测试异常
print("step0")
try:
print("step1")
a = 1 / 0
print("step2")
except BaseException as e:
print("发生异常step3")
print(e)
print(type(e))
print("step4")
#例子循环输入数字,如果不是数字则处理异常,直到输入88,则结束循环
while True:
try:
x=input("请输入一个数字")
print("输入的数字;",x)
if x==88:
print("退出程序")
break
except BaseException as e:
print("出现异常")
print(e)
print("程序结束")
try:
a=input("请输入一个被除数")
b=input("请输入一个除数")
c=float(a)/float(b)
except BaseException as e:
print(e)
else:
print(c)
finally:
print("无论是否发生异常,我都会执行")
print("程序结束")
# 打开文件
try:
f = open("c:/Users/FYL/Desktop/a.txt", "r")
content = f.readline()
print(content)
except:
print("未找到文件")
finally:
print()
f.close()
print("程序执行结束")
# 2.with上下文管理
with open("c:/Users/FYL/Desktop/a.txt") as f:
content = f.readline()
print(content)
print("程序执行结束")
# 3.定义异常类
class AgeError(Exception):
def __init__(self, errorInfo):
Exception.__init__(self)
self.errorIofo = errorInfo
def __str__(self):
return str(self.errorIofo) + "年龄错误"
###### 测试代码 ########
if __name__ == "__main__": # 如果为True,则模块作为独立文件运行,可以执行测试代码
age = int(input("输入一个年龄"))
if age < 1 or age > 150:
raise AgeError(age)
else:
print("正常的年龄:", age)
3.csv文件的操作读取和写入
import csv
with open("dd.csv","r")as f:
a_csv=csv.reader(f)
#print(list(a_csv))
for row in a_csv:
print(row)
with open("ee.csv","w")as f:
b_csv=csv.writer(f)
b_csv.writerow(["ID","姓名","年龄"])
c=[["1004","嘻嘻","3"],["1005","东东","4"]]
b_csv.writerows(c)
4.os模块调用操作系统文件和命令和os.path模块
import os
import os.path
os.system("notepad.exe")#调用记事本程序
os.startfile(r"E:\Software\QQ\Bin\QQScLauncher.exe")
#1.1 os模块-文件和目录操作
#1.1.1获取文件夹的相关属性
print(os.name)
print(os.sep)#分隔符
print(repr(os.linesep))#换行符
print(os.stat("test1.py"))#获取文件内容
#1.1.2关于工作目录的操作
print(os.getcwd())#获取当前的目录
os.chdir("d:")#改变当前的目录:d盘目录
os.mkdir("书籍")#然后建立了书籍文件夹
#1.1.3创建目录、创建多级目录、删除
os.rmdir("书籍")#相对路径都是相对当前的工作目录
os.makedirs("电影/港台/周星驰")#在多级目录建立文件夹
os.removedirs("电影/港台/周星驰")#只能删除空目录
os.makedirs("../音乐/香港/刘德华")#..是指的是在上一级目录建立文件夹
os.rename("电影","movie")#把文件电影重命名为movie
dirs=os.listdir("movie")#列出一级子目录一级文件夹
print(dirs)
#1.2对路径的操作
path=os.path.abspath("a.txt")
print(os.path.split(path))
# 列出工作目录下所有的.py文件,并输出文件名
path=os.getcwd()#获得当前目录
file_list=os.listdir(path)
for filename in file_list:
if filename.endswith("py"):
print(filename)
print("#########")
#列表式
filelist2=[filename for filename in os.listdir(path)if filename.endswith("py")]
for f in filelist2:
print(f,end="\t")
#1.3.walk()递归遍历所有的文件和目录
#os.walk()方法
all_file=[]
path=os.getcwd()
file2=os.walk(path)
for dirpath,dirname,filename in file2:
for dir in dirname:
# print(dir)
all_file.append(os.path.join(dirpath,dir))
for name in filename:
all_file.append(os.path.join(dirpath,name))
for file in all_file:
print(file)
#shutil模块(拷贝和压缩)
import shutil
shutil.copyfile("1.txt","1_copy.txt")
shutil.copytree("movie/港台","电影")
shutil.make_archive("电影/gg","zip","movie/港台")
#zip压缩\解压缩
import zipfile
z1=zipfile.ZipFile("d:/a.zip","w")
z1.write("1.txt")
z1.close()
z2=zipfile.ZipFile("d:/a.zip","r")
z2.extractall("电影")
z2.close()
5.递归算法
num=1
def a1():
global num#如果在函数内部改变全局变量的值,增加global关键字声明一下
num+=1
print("打印a")
if num<3:
a1()
def b1():
print("b1")
a1()
#使用递归计算n的阶乘
def factorial(n):
if n==1:
return n
else:
return n*factorial(n)
factorial(5)
#递归打印所有的目录和文件
import os
def getAllFile(path):
childFile=os.listdir(path)
for file in childFile:
filepath=os.path.join(path,file)
if os.path.isdir(filepath):
getAllFile(filepath)
print(filepath)
getAllFile("Day_1")