python——文件、os模块、异常,连接mysql

来源:互联网 发布:深圳证券交易所软件 编辑:程序博客网 时间:2024/06/03 04:38

一、文件

文件的操作流程:

1.打开 open

2.读写 read,write
3.关闭 close

默认情况下时只读的
1.文件模式
1)r    只读,若文件不存在会报错
2)r+    读写,若文件不存在会报错
In [70]: f = open("hello.txt","a+")
In [77]: f.write("hello")    #写是追加的
In [78]: f.read()        #此时无法读取文件内容,必须等文件关闭再进才会有

3)w    只写,若文件不存在,就创建,覆盖
4)w+    读写,若文件不存在,就创建,进去就清空文件,写完再读也看不到,关闭再以读的方式进去就可以读到

5)a    只写,若文件不存在,就创建,追加
6)a+    读写,若文件不存在,就创建,追加,进去就读,可以读,只要写了之后就读不了了,关闭之后在进才能读到

2.文件对象的方法

1)flush():提交新写入的内容

2)seek(偏移量,选项)    
    选项:0:start 2 end 1 current
    偏移量:>0right <0left


3)read:返回全部行
    In [127]: f.read()
    Out[127]: 'hellohhhhklk\nnihao'


4)readline:字符串
    In [130]: f.readline()
    Out[130]: 'hellohhhhklk\n'

    In [131]: f.readline()
    Out[131]: 'nihao'

    In [132]: f.readline()
    Out[132]: ''


5)readlines:列表
    In [138]: f.readlines()
    Out[138]: ['hellohhhhklk\n', 'nihao']


6)next:读完抛异常
    In [134]: f.next()
    Out[134]: 'hellohhhhklk\n'

    In [135]: f.next()
    Out[135]: 'nihao'

    In [136]: f.next()
    ---------------------------------------------------------------------------
    StopIteration                             Traceback (most recent call last)
    <ipython-input-136-c3e65e5362fb> in <module>()
    ----> 1 f.next()

    StopIteration:

7)write:
8)writelines:
    In [141]: l = ["one\n","two\n"]
    In [150]: f.writelines(l)

    In [151]: f.flush()

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

    In [158]: f.readlines()
    Out[158]: ['hellohhhhklk\n', 'nihaoone\n', 'two\n']


练习1:

找出文件中关键字的次数:

  1 #!/usr/bin/env python
  2 import re
  3 r = r"hello"
  4 f = open("/root/hello.txt","a+")
  5 print len(re.findall(r,f.read()))



二、os模块


1.os的一些方法:


1)os.mkdir(目录名,权限)    ##创建目录    mkdir
    In [189]: os.mkdir("osdir")

2)os.makedirs()        ##创建一系列目录    mkdir -p
    In [192]: os.makedirs("osdir/dir/dd/d")

3)os.remove()        ##删除一个文件    rm -fr
4)os.removedirs()
5)os.rmdir()    
6)os.listdir()        ##列出文件内容    ls
7)os.getcwd()        ##查看当前说在目录 pwd
8)os.chdir()        ##切换目录    cd
    In [210]: os.chdir("/")

    In [211]: os.getcwd()
    Out[211]: '/'

9)os.path.isdir()        ##是否是目录
    In [212]: os.path.isdir("/etc")
    Out[212]: True

10)os.path.isfile()    ##是否是文件
    In [216]: os.path.isfile("/etc/passwd")
    Out[216]: True

11)os.path.exists()    ##是否存在
    In [217]: os.path.exists("/etc/passwd")
    Out[217]: True

12)os.path.join()        ##连接两个部分成为一个路径
    In [218]: os.path.join("io","oi")
    Out[218]: 'io/oi'

13)os.path.split()        ##分割一个路径成为两部分
    In [219]: os.path.split("/etc/passwd")
    Out[219]: ('/etc', 'passwd')

14)os.path.getsize()    ##获得文件大小
    In [220]: os.path.getsize("/etc/passwd")
    Out[220]: 2323

15)os.walk()
    In [223]: ok = os.walk("/osdir")
    In [225]: ok.next()
    Out[225]: ('/osdir', ['d1'], ['file2'])



三、异常


所有的异常都继承与BaseException

1.捕获异常
      1 #!/usr/bin/env python
      2 try:
      3     open("helo")
      4     print a
      5 except IOError,msg:        #msg用来放错误的详细信息
      6     print "file is not exists"
      7 finally:
      8     print "haha happy!"
    [root@foundation29 code]# python yichang.py
    file is not exists
    haha happy!
2.抛出异常:
     10 class OtherError(BaseException):
     11     pass
     12 n = input("int:")
     13 if n == 0:
     14     raise OtherError("invalid value %s" %n)
     15 print 10/n
    int:0
    Traceback (most recent call last):
      File "yichang.py", line 14, in <module>
        raise OtherError("invalid value %s" %n)
    __main__.OtherError: invalid value 0
            
在主程序中捕获异常
     18 def hello():
     19     return a
     20 def westos():
     21     return hello()
     22 def main():
     23     try:
     24         westos()
     25     except NameError,msg:
     26         print "Error"
     27 main()
    [root@foundation29 code]# python yichang.py

    Error



四、mysql

1.安装mysql:
若出现以下错误,就卸载mariadb-libs.x86_64之后,再重新安装maridb-server

Error: Package: 1:mariadb-server-5.5.35-3.el7.x86_64 (rhel-dvd)
           Requires: mariadb-libs(x86-64) = 1:5.5.35-3.el7
           Installed: 1:mariadb-libs-5.5.44-2.el7.x86_64 (@anaconda/7.2)
               mariadb-libs(x86-64) = 1:5.5.44-2.el7
           Available: 1:mariadb-libs-5.5.35-3.el7.x86_64 (rhel-dvd)
               mariadb-libs(x86-64) = 1:5.5.35-3.el7
Error: Package: 1:mariadb-5.5.35-3.el7.x86_64 (rhel-dvd)
           Requires: mariadb-libs(x86-64) = 1:5.5.35-3.el7
           Installed: 1:mariadb-libs-5.5.44-2.el7.x86_64 (@anaconda/7.2)
               mariadb-libs(x86-64) = 1:5.5.44-2.el7
           Available: 1:mariadb-libs-5.5.35-3.el7.x86_64 (rhel-dvd)
               mariadb-libs(x86-64) = 1:5.5.35-3.el7
 You could try using --skip-broken to work around the problem
 You could try running: rpm -Va --nofiles --nodigest

2.安装后启动maridb服务

3.安装MySQL-python.x86_64

4.连接数据库与python


    1)先在数据库中建立一个库,表
    MariaDB [(none)]> create database westos;
    MariaDB [(none)]> use westos
    MariaDB [westos]> create table userinfo (
        -> username varchar(10),
        -> passwd varchar(10)
        -> )
        -> ;
    Query OK, 0 rows affected (0.34 sec)
    MariaDB [westos]> insert into userinfo value("hello","123")
        -> ;
    Query OK, 1 row affected (0.30 sec)
    MariaDB [westos]> select * from userinfo;
    +----------+--------+
    | username | passwd |
    +----------+--------+
    | hello    | 123    |
    | westos   | 456    |
    | fentiao  | 789    |
    +----------+--------+
    3 rows in set (0.00 sec)
    2)进入ipython
    In [233]: import MySQLdb    ##导入数据库包
    In [237]: conn = MySQLdb.connect(user="root",passwd="",db="westos",host="localhost",charset="utf8")#建立连接
    In [238]: cur = conn.cursor()    ##获得游标

    In [240]: cur.execute("select * from userinfo;")#用游标执行sql语句
    Out[240]: 3L
    In [242]: cur.fetchone()    #得到上面执行结果的第一个
    Out[242]: (u'hello', u'123')

    In [243]: cur.fetchone()    #得到上面执行结果的下一个
    Out[243]: (u'westos', u'456')

    In [244]: cur.fetchone()    
    Out[244]: (u'fentiao', u'789')

    In [245]: cur.fetchone()    #没有了就不会再显示

    In [246]: cur.scroll(0,"absolute")#将游标回滚到开始

    In [247]: cur.fetchmany(3)    #得到3个结果
    Out[247]: ((u'hello', u'123'), (u'westos', u'456'), (u'fentiao', u'789'))

    In [248]: cur.fetchmany(2)    #得到两个
    Out[248]: ()

    In [249]: cur.scroll(0,"absolute")    #回滚

    In [250]: cur.fetchmany(2)
    Out[250]: ((u'hello', u'123'), (u'westos', u'456'))
    In [252]: cur.execute('insert into userinfo value("hello1","123")')
    Out[252]: 1L
    In [253]: conn.commit()        #提交所作的操作
        MariaDB [westos]> select * from userinfo;
        +----------+--------+
        | username | passwd |
        +----------+--------+
        | hello    | 123    |
        | westos   | 456    |
        | fentiao  | 789    |
        | hello1   | 123    |
        +----------+--------+
        4 rows in set (0.00 sec)

    In [255]: cur.execute(sqli,("hello2","234"))#将语句放到sqli变量里执行
    Out[255]: 1L

    In [256]: conn.commit()
        MariaDB [westos]> select * from userinfo;
        +----------+--------+
        | username | passwd |
        +----------+--------+
        | hello    | 123    |
        | westos   | 456    |
        | fentiao  | 789    |
        | hello1   | 123    |
        | hello2   | 234    |
        +----------+--------+
        5 rows in set (0.00 sec)


    In [257]: cur.executemany(sqli,[("hello4","345"),("hello3","456")])#执行多条语句
    Out[257]: 2L

    In [258]: conn.commit()

        MariaDB [westos]> select * from userinfo;
        +----------+--------+
        | username | passwd |
        +----------+--------+
        | hello    | 123    |
        | westos   | 456    |
        | fentiao  | 789    |
        | hello1   | 123    |
        | hello2   | 234    |
        | hello4   | 345    |
        | hello3   | 456    |
        +----------+--------+
        7 rows in set (0.00 sec)
    In [259]: cur.close()#关闭连接时应该先关游标,再关闭连接

    In [260]: conn.close()




五、类
      1 #!/usr/bin/env python
      2 class student(object):
      3     def __init__(self,name,score):    #在其它语言中,self 称为“this”
      4         self.name = name
      5         self.score = score
      6     def getScore(self):
      7         print "%s:%s" %(self.name,self.score)
      8 std1 = student("hh",123)
      9 std2 = student("kk",89)
     10 std1.getScore()
     11 std2.getScore()
    [root@foundation29 code]# python student.py
    hh:123
    kk:89
私有变量:__name,只有在类里面才可以修改

  1 #!/usr/bin/env python
  2 class student(object):
  3     def __init__(self,name,score):
  4         self.__name = name        #定义__name为私有变量
  5         self.__score = score
  6     def getScore(self):
  7         print "%s:%s" %(self.__name,self.__score)
  8 std1 = student("hh",123)
  9 std2 = student("kk",89)
 10 std1.getScore()
 11 std2.getScore()
 12 std1._student__name = "cat"            #无法修改私有变量,输出仍为以前的值
 13 print std1.__name

双下划线开头的实例变量是不是一定不能从外部访问呢?其实也不是。不能直接访问 __name
是因为 Python 解释器对外把 __name 变量改成了 _Student__name ,所以,仍然可以通过
_Student__name 来访问 __name 变量:


1.继承和多态
当子类重写了父类的方法,就执行子类的方法
  1 #!/usr/bin/env python
  2 class Student(object):
  3     def run(self):
  4         print "student running ... "
  5 class Junior(Student):
  6     def hello(self):
  7         print "junior running ... "
  8 std1 = Junior()
  9 std1.run()
当子类没有重写父类的方法,就执行父类的方法
  1 #!/usr/bin/env python
  2 class Student(object):
  3     def run(self):
  4         print "student running ... "
  5 class Junior(Student):
  6     def hello(self):
  7         print "junior running ... "
  8 std1 = Junior()
  9 std1.run()




练习题1:
求一个文件中某个关键字的出现的次数
  1 #!/usr/bin/env python
  2 import re
  3 key = raw_input("please input key:")
  4 r = r"%s" %key
  5 f = open("/root/hello.txt","a+")
  6 count = 0
  7
  8 for line in f.readlines():
  9     count += len(re.findall(r,line))
 10 print key,"appears",count,"times in /root/hello.txt"
练习题2:
置换一个文件中的关键字,并把最终结果放到另一个文件
  1 #!/usr/bin/env python
  2 import re
  3 f1 = open("/root/hello.txt","a+")
  4 f2 = open("fu.txt","a+")
  5 f2.write(f1.read().replace("hello","westos"))
  6 f1.close()
  7 f2.close()
~                       


练习题3:
递归遍历目录:
方法一:
In [232]: for dir,ddir,fdir in os.walk("/osdir"):
    for filename in fdir:
        print os.path.join(dir,filename)
   .....:         
/osdir/file2
/osdir/d1/file3
/osdir/d1/d2/hhh
方法二:
  1 #!/usr/bin/env python
  2 import os
  3 path = raw_input("please input directory:")
  4
  5 def diguiLs(path):
  6     if os.path.isfile(path) or os.listdir(path) == []:
  7         print path
  8     else:
  9         dl = os.listdir(path)
 10         for i in dl:
 11             diguiLs(path+"/"+i)
 12 diguiLs(path)

0 0
原创粉丝点击