python学习第四讲

######################
    文件
######################

1.打开文件
    r    ##只读模式(默认模式) 若文件不存在会报错
    r+    ##可读可写    若文件不存在会报错    (从开头开始覆盖原有)
    w    ##只写模式    若文件不存在会创建文件
    w+    ##可读可写    若文件不存在会创建文件
    a    ##只读(追加模式)
    a+    ##可读可写
    
    In [2]: f = open("hello.txt",'r')

    In [3]: f.read()
    Out[3]: 'hello jet\n'

    In [4]: f.read()    ##第二次读取指针读到末尾,所以读不出来内容
    Out[4]: ''

    In [5]: f.close()    ##关闭文件

    In [6]: f = open("hello.txt",'r+')

    In [7]: f.read()
    Out[7]: 'hello jet\n'

    In [8]: f.write("jet hello")

    In [9]: f.close()

    In [10]: f = open("hello.txt","r")

    In [11]: f.read()
    Out[11]: 'hello jet\njet hello'

    In [12]: f.clo
    f.close   f.closed  

    In [12]: f.close()

    In [13]: f = open("hello",'w')

    In [14]: f.read()    ##只写模式
    ---------------------------------------------------------------------------
    IOError                                   Traceback (most recent call last)
    <ipython-input-14-bacd0e0f09a3> in <module>()
    ----> 1 f.read()

    IOError: File not open for reading

    In [15]: f.write("wula")

    In [17]: f.close()
    In [22]: f = open("jet",'a+')

    In [23]: f.read()
    Out[23]: 'hi jet'

    In [24]: f.write("wula")     ##直接追加在原有字符后面,若要换行\n

    In [28]: f.close()

    In [29]: f = open("jet",'r')

    In [30]: f.read()
    Out[30]: 'hi jetwula'
###########################################
2.文件的操作
    f.seek(pianyi,xuanxiang)    ##选项=0,为开头位置;选项=2,为末尾位置;选项=1,当前位置
                    ##偏移>0,向右;偏移<0,向左;

    f.flush()        ##当写入后不需要关闭文件,即可写入。
    
    f.read()
    f.readline()
    f.next()
    f.readlines()
    
    f.write()    ##单行写入
    f.writelines()    ##多行写入
    
    f.tell()    ##现在指针所处位置

    In [13]: f = open("jet.txt",'r+')
    In [14]: f.read()
    Out[14]: 'hello jet'
    In [15]: f.read()
    Out[15]: ''
    In [16]: f.seek(0,0)    ##将指针移到开头
    In [17]: f.read()
    Out[17]: 'hello jet'
    In [18]: f.seek(0,2)    ##将指针移到末尾
    In [19]: f.read()
    Out[19]: ''
    In [20]: f.write("\njet hello")
    In [22]: f.flush()
    In [24]: f.seek(0,0)
    In [25]: f.read()
    Out[25]: 'hello jet\njet hello'
    In [26]: f.seek(0,0)
    In [27]: f.readline()    ##迭代读取类似f.next
    Out[27]: 'hello jet\n'
    In [28]: f.readline()
    Out[28]: 'jet hello'
    In [29]: f.seek(0,0)
    In [30]: for i in f.readlines():    ##生成一列表
       ....:     print i
       ....:     
    hello jet

    jet hello

    In [42]: f = open("hello.txt")

    In [43]: f.read()
    Out[43]: 'wuwuuwuwt\njet hello'   

    In [45]: f.tell()
    Out[45]: 19

    In [46]: f.seek(0,0)

    In [47]: f.tell()
    Out[47]: 0


练习:
    #!/usr/bin/env python
    #coding=utf-8
    import re
    import os
    filename = raw_input("请输入打开的文件名称:")
    gui = raw_input("输入你需要查看的关键字:")
    f = open(filename,'r+')
    j = 0
    for i in f.readlines():
        if re.findall(gui,i):
        j += 1
        else:
        pass
    print "%s共有重复了%s次" %(gui,j)

3.os模块
    In [65]: os.mkdir("/home/kiosk/Desktop/wula")    ##创建目录

    In [66]: os.makedirs("/home/kiosk/Desktop/wu/pp")    ##==mkdir -p xxx/xx/

    In [67]: os.removedirs("/home/kiosk/Desktop/wu/pp")    ##删除多个

    In [68]: os.rmdir("/home/kiosk/Desktop/wula")    ##删除单个

    In [69]: os.listdir("/home/kiosk/")    ##列出该目录下的所有
    Out[69]:
    ['.mozilla',
     '.bash_logout',
     '.bash_profile',
     '.bashrc',
     '.config',
     '.ssh',
     '.cache',
     'Desktop',
     'Downloads',
     'Templates',
     'Public',
     'Documents',
     'Music',
     'Pictures',
     'Videos',
     '.ICEauthority',
     '.local',
     '.esd_auth',
     '.vnc',
     '.fltk',
     '.bash_history',
     '.PyCharm40',
     '.java',
     '.gnome',
     'PycharmProjects',
     '.gnome2',
     '.matplotlib',
     'pycharm-community-4.0.1',
     '.ipython',
     'jetStudy',
     '.gnome2_private',
     '.viminfo']

    In [70]: os.getcwd()        ##当前ipython所处位置
    Out[70]: '/home/kiosk/Desktop'

    In [71]: os.chdir("/mnt/")    ##切换ipython位置,实际的shell位置不变

    In [72]: os.getcwd()
    Out[72]: '/mnt'
    In [83]: os.path.join("/home/kiosk/","jet")
    Out[83]: '/home/kiosk/jet'

    In [84]:

    In [84]: os.path.getsize("/etc/pa")
    /etc/pam.d/   /etc/passwd   /etc/passwd-  

    In [84]: os.path.getsize("/etc/pass")
    /etc/passwd   /etc/passwd-  

    In [84]: os.path.getsize("/etc/passwd")
    Out[84]: 2368

    In [85]: g = os.walk("/home/kiosk/Desktop/wula/")

    In [86]: g
    Out[86]: <generator object walk at 0x170b5a0>

    In [87]: g.next()
    Out[87]: ('/home/kiosk/Desktop/wula/', ['jet'], ['wula1', 'wula2'])

    In [88]: for dir,sdir,file in os.walk("h")
    %%html    %hist     %history  hasattr   hash      help      hex       

    In [88]: for dir,sdir,file in os.walk("/home/kiosk/Desktop/wula/"):
       ....:     for filename in file:
       ....:         print os.path.join(dir,filename)
       ....:         
    /home/kiosk/Desktop/wula/wula1
    /home/kiosk/Desktop/wula/wula2
    /home/kiosk/Desktop/wula/jet/jet1
    /home/kiosk/Desktop/wula/jet/jet2
    /home/kiosk/Desktop/wula/jet/zhang/zhang1
    /home/kiosk/Desktop/wula/jet/zhang/zhang2
    os.path.exist("路径")

4.数据库操作
    4.1 前期准备
      655  yum install mariadb-server.x86_64 -y
      656  systemctl start mariadb.service
      658  mysql_secure_installation
      659  yum search mysql |grep python
      660  yum install MySQL-python.x86_64 -y
    
    4.2操作
    conn = MySQLdb.connect(user='root',passwd='1234',db='linux',host='localhost',charset='utf8')    ##连接数据库
    cur = conn.cursor()                        ##返回一个游标
    cur.execute("select * from userinfo;")        ##()里面写操作语句
    cur.fetchone()                ##第归输出
    cur.scroll(0,"absolute")        ##游标回0
    cur.fetchmany(3)        ##输出多项(n)
    cur.execute('insert into userinfo value("amei","123");')    ##单条插入
    conn.commit()                ##更新数据
    sqli = "insert into userinfo value(%s,%s)"    ##插入语句
    cur.execute(sqli,("mengnai","123"))    ##单条操作
    conn.commit()
    cur.executemany(sqli,[("mengna11","123"),("safsa","sge")])    ##多条插入
    cur.execute(' userinfo set logintime="2017213213" where username="jet";')    ##更改数据
    cur.execute('delete from userinfo  where username="jet";')    ##删除数据
    conn.commit()
    cur.close()        ##关闭游标
    conn.close()        ##关闭

5.异常处理
    捕获异常:
    #!/usr/bin/env python
    #coding=utf-8


    try:
        print 1
        open("hello")

    except IOError,msg:
        print "the file not exist"

    except NameError,msg:
        print "the variable is not define"
    
    finally:
        print "hello"

    抛出异常:
    n = input("int:")        ##系统抛出
    if n == 0:
        raise NameError("invaild value:%s" %n)
    print 10/n

    [kiosk@foundation24 python05Code]$ python try.py
    int:0
    Traceback (most recent call last):
      File "try.py", line 21, in <module>
        raise NameError("invaild value:%s" %n)
    NameError: invaild value:0
    [kiosk@foundation24 python05Code]$ python try.py
    int:4
    2
    [kiosk@foundation24 python05Code]$ vim try.py
        class OtherError(BaseException):    ##自定义抛出
            pass


        n = input("int:")
        if n == 0:
            raise OtherError("invaild value:%s" %n)
        print 10/n

    [kiosk@foundation24 python05Code]$ python try.py
    int:0
    Traceback (most recent call last):
      File "try.py", line 28, in <module>
        raise OtherError("invaild value:%s" %n)
    __main__.OtherError: invaild value:0
    [kiosk@foundation24 python05Code]$


6.类
    example1:
        #!/usr/bin/env python
        #coding=utf-8

        class Student(object):
            def __init__(self,name,score):
                self.name = name
                self.score = score
            def printscore(self):
                print "姓名:%s\n成绩:%s" %(self.name,self.score)


        std1 = Student("jet","100")
        std2 = Student("qinyu","09")


        std1.printscore()
        std2.printscore()

    example2:
        #!/usr/bin/env python
        #coding=utf-8

        class Student(object):
            def __init__(self,name,score):
                self.__name = name        ##建议不要随便更改变量
                self.__score = score
            def printscore(self):
                print "姓名:%s\n成绩:%s" %(self.__name,self.__score)

            def get_name(self):
                print self.__name

        std1 = Student("jet","100")
        std2 = Student("qinyu","09")
        std1.name = "zhangxinli"
        std1.get_name()

        [kiosk@foundation24 python05Code]$ python student.py
        jet

                
    








  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值