python_day3(文件处理)

1、文件处理

#Author:Elson Zeng
#data = open("test").read()
# f = open("test",'a',encoding='utf-8')  #文件句柄

#f = open("test","a",encoding="utf-8") #文件句柄 追加(源文件)

#f = open("test","r+",encoding="utf-8") #文件句柄 读写(源文件)
#f = open("test","w+",encoding="utf-8")  #文件句柄 写读(新文件)
#f = open("test","wb") #文件句柄 二进制文件
 # #a = appen追加 # data = f.read() # # print(data) # # print('data') # f.write("
我爱你") # f.close() f = open("test",'r',encoding="utf-8") #print(enumerate(f.readlines())) #high bige count = 0 for line in f: #f为一个迭代器 if count == 2 : print("___") print(line.strip()) count += 1 #low loop """ for index,line in enumerate(f.readlines()): print(line.strip()) if index == 1: print("_____") """
#光标位置(按字符计算位置)
print(f.tell())
#光标返回
f.seek(0)
print(f.readline())
#打印文件名
print(f.name)
#实时写入硬盘
f.flush()

#截断(字符串)
f.truncate(20)
import sys,time
for i in range(20):
    sys.stdout.write("#")
    sys.stdout.flush()
    time.sleep(0.2)

 2、文件增删改

#Author:Elson Zeng

f = open("test",'r',encoding="utf-8")
f2 =  open("test_modify.txt",'w',encoding="utf-8")

for line in f:
    if "取离别时的你" in line:
        line = line.replace("取离别时的你","取离别时的航健")
    f2.write(line)
f.close()
f2.close()

 3、字符编码与转发

#Author:Elson Zeng
#python3默认字符编码是unicode
#decode解码(只针对unicode,写现在的类型)
#encode编码(写转换的类型)
s = "你好"
s_to_gbk = s.encode("gbk")
print(s_to_gbk)
print(s_to_gbk.decode("gbk").encode("utf-8"))

 4、函数

1.面向对象 ==> 类 ==> class

2.面向过程 ==> 过程 ==> def 

3.面向函数编程 ==> 函数==> def 

#函数def
def fun1():
    #文档介绍
    print ("a")
    return 0

#过程def
def fun2():
    #文档介绍
    print("b")

x = fun1()
y = fun2()
print("from funt1: %s"%x)
print("from funt2: %s"%y)

 函数非固定参数

#*args :接受N个位置参数,装换成元组的方式
def test(*args):
    print(args)

test(*[12,3])

#**kwargs: 接受N个关键字参数,装换成字典的方式
def test2(**kwargs):
    print(kwargs)
    print(kwargs['name'])

test2(**{'name':"elson",'age':18})

def test3(name,**kwargs):
    print(name)
    print(kwargs)

test3('elson',age=18)

 全局变量

school = "1111"
#声明全局变量(字典、列表、类都能在局部改变量)
def test():
global school
school = "Old the boy"

test()
print(school)

5、递归

def calc(n):
    print(n)
    if int(n/2) ==0:
        return n
    return calc(int(n/2))
 
calc(10)

递归特性:

1. 必须有一个明确的结束条件

2. 每次进入更深一层递归时,问题规模相比上次递归都应有所减少

3. 递归效率不高,递归层次过多会导致栈溢出(在计算机中,函数调用是通过栈(stack)这种数据结构实现的,每当进入一个函数调用,栈就会加一层栈帧,每当函数返回,栈就会减一层栈帧。由于栈的大小不是无限的,所以,递归调用的次数过多,会导致栈溢出)

原文地址:https://www.cnblogs.com/elson-zeng/p/10897689.html