首页 > 技术文章 > python初学小结三:文件、集合、函数、变量等

Ceciliamumu 2017-10-19 19:22 原文

一、文件操作:

文件操作流程:

1、打开文件,得到文件句柄并赋值给一个变量

2、通过句柄对文件进行操作

3、关闭文件

打开文件的模式有:

  • r,只读模式(默认)。
  • w,只写模式。【不可读;不存在则创建;存在则删除内容;】
  • a,追加模式。【可读;   不存在则创建;存在则只追加内容;】

"+" 表示可以同时读写某个文件

  • r+,可读写文件。【可读;可写;可追加】
  • w+,写读
  • a+,同a

"U"表示在读取时,可以将 \r \n \r\n自动转换成 \n (与 r r+ 模式同使用)

  • rU
  • r+U

"b"表示处理二进制文件(如:FTP发送上传ISO镜像文件,linux可忽略,windows处理二进制文件时需标注)

  • rb
  • wb
  • ab

 

原文件yesterday2:

 

 

(1)读取文件

f = open("yesterday2",'r',encoding= "utf-8")#文件句柄,'r'是读模式,不写,默认是'r','w'写是创建一个文件,原来文件就没了

data2 = f.read()

print('------data2------\n',data2)

执行结果:

 

 

(2)for循环读取文件

for i in range(3) :
   print(f.readline() )#每次读一行,一共读三行
for line in f.readlines() :
    print(line.strip())  #strip()把空格与换行去掉

运行前原文件yesterday2

 

 

执行结果:

 

 

(3)写文件

f = open("yesterday2",'w',encoding= "utf-8")

f.write("black black heart\n")#'w'写是创建一个文件,原来文件的内容就没了
f.write("why would you offer more\n")
f.write("Why would you make it easier on me to satisfy")

执行结果:

 

 

4

f = open("yesterday2",'r',encoding= "utf-8")

print(f.readlines() )#变成每行是一个元素的列表['black black heart\n', 'why would you offer more\n', 'Why would you make it easier on me to satisfy']

5

f.readlines()只适合读小文件,因为读时先加载完一次性全读到内存

所以可以使用循环,读一行,删除一行,内存中只保存一行,就可以处理大文件了:

count = 0

f = open("yesterday",'r',encoding= "utf-8")

for line in f:

    if count ==4:

        print('----------我是分割线-------')

        count += 1

        pass

print(line.strip())

count +=1

f.close()

执行结果:

 

图(5)-1

注意:若上述代码中的“pass”改写成“continue”,执行结果如下:

 

图(5)-2

对比图(5)-1图(5)-2,发现后者少了一句:“If you call your friends and nobody's home. 如果你打电话给朋友却没有一人在家 ”,这是因为passcontinue的执行机制不同,当count ==4成立时,pass之后会执行下面的print(line.strip()),而continue之后,程序跳转到 if count ==4:,所以会少打印一行。

6)读写r+

f = open("yesterday2", 'r+', encoding="utf-8")#读写

print(f.readline())

print(f.readline())

print(f.readline())

print(f.tell())

f.write("\n-------add one line-----------\n")#写在文件最后

print(f.readline() )

执行结果:

 

 

原来文件变成:

 

 

(7)二进制文件读rb

f = open("yesterday2", 'rb')#二进制文件读

print(f.readline() )

print(f.readline() )

print(f.readline() )

执行结果:

 

 

(8)修改文件

"""修改文件时,新建立一个文件,修改好的文件出现在新文件中"""

f = open("yesterday2","r",encoding= "utf-8")

f_new = open("yesterday2.bak","w",encoding= "utf-8")

 

for line in f:

    if "经历了风暴忍受了孤独" in line:

        line = line.replace("经历了风暴忍受了孤独","历经过风雨忍受过孤独")

    f_new.write(line )

f.close()

f_new .close()

执行之后,新建立了一个文件yesterday2.bak:

 

 

(9)With语句:执行完后自动关闭文件

语法:

with open("yesterday2","r",encoding= "utf-8") as f ,\

open("yesterday2","r",encoding= "utf-8") as f2:

python规范:一行代码不要超过80个字符,故打开多个文件可以用“\”写成多行

二、进度条小程序:

import sys ,time

for i in range (20):

    sys.stdout.write("#")

    sys.stdout.flush()

time.sleep(0.1)

三、集合

list_1 = [1,2,5,3,2,6,4,2,6]

list_1 = set (list_1)#把列表变成集合,集合是无序不重复的

list_2 = set([2,5,33,22,1])

 

print(list_1 ,list_2 )#{1, 2, 3, 4, 5, 6} {33, 2, 1, 5, 22}

print(list_1 ,type(list_1 ))#{1, 2, 3, 4, 5, 6} <class 'set'>

 

#交集

print(list_1 .intersection(list_2 ))#=print(list_1 & list_2 )#{1, 2, 5}

 

#并集

print(list_1 .union(list_2) )#=print(list_1 | list_2 )#{1, 2, 3, 4, 5, 6, 33, 22}

 

#差集

print(list_1 .difference(list_2 ) )#=print(list_1 - list_2 )#{3, 4, 6}

 

#子集

list_3 = set([1,2,5])

print(list_3 .issubset(list_2 ))#True

 

#对称差集,取出两集合里面互相都没有的取出来

print(list_1 .symmetric_difference(list_2 ) )#=list_1^list_2#{33, 3, 4, 22, 6}

 

list_3 = set([1,2,5])

list_4 = set([4,6,8])

print(list_3 .isdisjoint(list_4 ) )#如果list_3list_4没有交集返回True#True

 

list_1 .add(889)#添加一项

list_1 .update([123,234,345])#添加多项,=list_1 .update({123,234,345})

print(list_1 )#{1, 2, 3, 4, 5, 6, 345, 234, 889, 123}

四、局部变量与全局变量

names = ["Lili","Vae","Cici"]

def change_name():

    names[0] = "李立"#列表,集合,字典可以在局部里面改全局变量的,(元组本来就不可更改,字符串,整数不可改)

    print("inside func",names)

change_name()

print("outside func", names)

执行结果:

inside func ['李立', 'Vae', 'Cici']

outside func ['李立', 'Vae', 'Cici']

五、一个高阶函数的例子

def add(a,b,f):

    return f(a)+f(b)

res = add (3,-6,abs)   #abs:Return the absolute value of the argument.

print(res )      #9

六、一个递归的例子

def calc(n):

    print(n)

    if int(n / 2) == 0:

        return n

    return calc(int(n/2))

calc(10)    #10  5  2  1

七、

1、函数与过程

#函数

def func1():

    """testing1,这是一个函数"""

    print('in the func1')

    return 0

#过程,过程就是没有返回值的函数

def func2():

    '''testing2,这是一个过程'''

    print('in the func2')

 

x = func1()#输出:in the func1

y = func2()#输出:in the func1

 

print('from func1 return is %s'%x)#输出from func1 return is 0

print('from func1 return is %s'%y)#输出:from func1 return is None

2、函数调用

import time

def logger():

    time_format = '%Y-%m-%d %X'#格式:年月日时分秒

    time_current = time .strftime(time_format )# Convert a time tuple to a string according to a format specification.

    with open('a.txt','a+') as f:

        f.write('%s end action\n'%time_current )

def test1():

    print('test1 starting action...')

logger()

 

test1()   #test1 starting action...

同时新建一个文件a.txt

 

 

3、函数返回值:

def test1():

    print('in the test1')

 

def test2():

    print('in the test2')

    return 0

 

def test3():

    print('in the test3')

    return 1,'hello',['Bob','lili'],{'name':'Bob'}

 

y = test2()

z = test3()

print(test1())#None

print(y)#0

print(z)#(1, 'hello', ['Bob', 'lili'], {'name': 'Bob'})return多于一个返回一个元组

4、函数的默认参数

#默认参数特点:调用函数时,默认参数非必须传递

用途:1def test(x,soft1=True,soft2=True),在默认安装值时,如果在逻辑判断时soft1=True,默认安装soft1

       2:连接数据库:def conn(host,port=3301)

                          pass

          主机指定默认端口号

1

def test(x,y=2):

    print(x)

    print(y)

test(1,y=3)#1 3

(2)参数组

1def test(*args):

    print(args )

 

test(1,2,3,4,5,4)     #(1, 2, 3, 4, 5, 4   )实参不固定时,将接受的实参放到元组

test(*[1,2,3,4,5])     #(1, 2, 3, 4, 5)  即:args=tuple([1,2,3,4,5])

2def test1(x,*args):

    print(x)

    print(args)

test1(1,2,3,4,5,6,7)  # 1  2,3,4,5,6,7

3#**kwargsn个关键字参数转换成字典的方式,key:value,key:value...

def test2(**kwargs ):

    print(kwargs )

    #print(kwargs['name'])

    #print(kwargs['age'])

    #print(kwargs['sex'])

 

test2(name='lili',age=22,sex='Y')#{'name': 'lili', 'age': 22, 'sex': 'Y'}

test2(**{'name':'vae','age':31,'sex':'Y'})#{'name': 'lili', 'age': 22}

 

分别用4print输出结果一次如下:

a{'name': 'lili', 'age': 22, 'sex': 'Y'}   {'name': 'vae', 'age': 31, 'sex': 'Y'}

blili  vae

c22  31

dY   Y

def test3(name,**kwargs ):

    print(name)

    print(kwargs )

test3('cecila',age=22,sex='Y')

输出:cecila   {'age': 22, 'sex': 'Y'}

 

# *args:接收N个位置参数,转换成元组,**kwargs接收关键字参数,转换成字典

def test5(name,age=22,*args,**kwargs ):

    print(name)#vae

    print(age)#31

    print(args)#输出:()

    print(kwargs )#{'sex': 'Y', 'hobby': 'book'}

test5('vae',sex='Y',hobby='book',age=31)

 

推荐阅读