1. 程式人生 > >python讀寫檔案模組

python讀寫檔案模組

一 往一個檔案寫資料

1 程式碼CodeInFile.py

# -*- coding:utf-8 -*-
class CodeInFile():
    def __init__(self,name,code,database):
        self.rootdir='E:\Python\MySQLControler'
        File=open('%s/code'%self.rootdir,'w')
        File.write('%s\t'%name)
        File.write('%s\t'%code)
        File.write('%s'%database)
        File.close()
if __name__=='__main__':
    test=CodeInFile('root','123456','test')

2 測試結果

root    123456    test

二 從檔案讀資料

1 程式碼ReadCode.py

# -*- coding:utf-8 -*-
class ReadCode():
    def __init__(self):
        self.rootdir = 'E:\Python\MySQLControler'
        File=open('%s/code'%self.rootdir,'r')
        self.Line=File.readline().split()
        File.close()
    def return_line(self):
        return self.Line
if __name__=='__main__':
    test=ReadCode()
    print test.return_line()

2 測試結果

D:\Python27\python.exe E:/Python/MySQLControler/WriteAndReadFile/ReadCode.py
['root', '123456', 'test']

三 從檔案讀出資料用來連線資料庫

1 程式碼Connect.py

# -*-coding:utf-8 -*-
import MySQLdb
from ReadCode import ReadCode
class Connect():
    def __init__(self,database,sql):
        readcode=ReadCode()
        name=readcode.return_line()[0]
        code=readcode.return_line()[1]
        db=MySQLdb.connect("localhost","%s"%name,"%s"%code,"%s"%database)
        cursor=db.cursor()
        try:
            cursor.execute(sql)
db.commit()
        except:
            db.rollback()
        db.close()
if __name__=='__main__':
    test=Connect("test","insert into create_user(email) "
                        "VALUES('
[email protected]
')")

2 測試結果