Python study notes, python notes

Source: Internet
Author: User

Python study notes, python notes

Python learning notes are mainly used to do trivial things in python.

Read and Write txt, read and write excel, read and write xml, Access Database

 

Using python to read and write excel files, we mainly reference xlrd and xlwt. Both xls and xlsx can be opened. Using xlrd to read excel files is not exclusively read, the excel file can still be opened during reading. Only xls can be written in excel.

Import xlrdimport xlwtimport xmlfrom xml. dom import minidomimport OS # simple IO operation to save txtdef createtxt (): ls = OS. linesep # get filename while True: fname = input ('enter filename: ') if OS. path. exists (fname): print ("error: '% s' already exists" % fname) else: break; # get file content (text) lines all = [] print ("\ nEnter lines ('. 'by itself to quit ). \ n ") # loop until user terminates input while True: entry = input ('>') if en Try = '. ': break else: all. append (entry) # write ines to file with proper line-ending fobj = open (fname, 'w') fobj. writelines (['% s % s' % (x, ls) for x in all]) fobj. close () print ('done! ') F = open (fname, 'R') for l in f. readlines (): print (l, end = '') # An Extra blank line in this place should be the reason for bom in windows # Read/Write exceldef rwexcel (): path = r'c: \ Users \ huach \ Desktop \ Right Bank traffic cave-Pressure Calculation .xlsx 'file = xlrd. open_workbook (path) # open the file sheet = file. sheet_by_index (0) # obtain the first sheet based on the index # sheet = file. sheet_by_name ('pe1-1') nc = sheet. ncols # obtain the number of sheet columns nr = sheet. nrows # Number of sheet rows newbook = xlwt. workbook () # create an excel Object nsheet = newbook. add_sheet ('testsheet ', cell_overwrite_ OK = True) # Add a sheet for I in range (20): row = sheet. row_values (I) # obtain row I. This is an array for j in range (nc): print (row [j], end = '') nsheet. write (I, j, row [j]) # print () newfile = r 'C: \ Users \ huach \ Desktop \ test.xls 'if OS. path. exists (newfile): OS. remove (newfile) # If yes, the newbook is deleted. save (newfile) # save the newly created excel Object # read/write xmldef xml (): # import xml. dom. minidom impl = minidom. getDOMImplementation () # create an xml Object dom = impl. createDocument (None, 'root', None) # create dom Root = dom.doc umentElement # root node root. setAttribute ('attr', 'root') # attribute for I in range (1, 3): employee = dom. createElement ('Employee') # Add a subnode employee. setAttribute ('attr', 'Child ') # Add attribute value = dom. createTextNode ('value') employee. appendChild (value) # Add the value root. appendChild (employee) # Save file = r'c: \ Users \ huach \ Desktop \ test. xml 'if OS. path. exists (file): OS. remove (file) # If yes, the f = open (file, 'A') dom is deleted. writexml (f, addindent = '', newl = '\ n') f. close () print ('xml written successfully') # Read dom = minidom. parse (file) root = dom.doc umentElement EMS = root. getElementsByTagName ('Employee') for em in EMS: attr = em. getAttribute ("attr") # Attribute print ('em. attr = % s' % attr) print ('em. attr = % s' % em. firstChild. data) # Value
# Access mssql and reference pymssql. This is a simple encapsulation of others and can be used directly. It is okay to add, delete, query, and modify a simple query. Thanks for your originality. · import pymssqlclass MSSQL: "For pymssql simple encapsulation pymssql library, the library here download: http://www.lfd.uci.edu /~ When using the gohlke/pythonlibs/# pymssql library, you must enable the TCP/IP protocol in SQL Server Configuration Manager: "" def _ init _ (self, host, user, pwd, db): self. host = host self. user = user self. pwd = pwd self. db = db def _ GetConnect (self): "Returned connection information: conn. cursor () "" if not self. db: raise (NameError, "no database information set") self. conn = pymssql. connect (host = self. host, user = self. user, password = self. pwd, database = self. db, charset = "utf8") c Ur = self. conn. cursor () if not cur: raise (NameError, "failed to connect to Database") else: return cur def ExecQuery (self, SQL ): "execution of the query statement returns a list containing tuple. The list element is the record row, and the tuple element is the example of calling the fields recorded in each row: ms = MSSQL (host = "localhost", user = "sa", pwd = "123456", db = "PythonWeiboStatistics") resList = ms. execQuery ("SELECT id, NickName FROM WeiBoUser") for (id, NickName) in resList: print str (id), NickName "" cur = self. _ GetConnect () cur.exe c Ute (SQL) resList = cur. fetchall () # The connection to self must be closed after the query is complete. conn. close () return resList def ExecNonQuery (self, SQL): "example of executing a non-query statement call: cur = self. _ GetConnect () cur.exe cute (SQL) self. conn. commit () self. conn. close () "" cur = self. _ GetConnect () cur.exe cute (SQL) self. conn. commit () self. conn. close () def main (): # MS = MSSQL (host = "localhost", user = "sa", pwd = "123456", db = "PythonWeiboStatistics ") ### the returned result is an l containing tuple. Ist, the list element is the record row, and the tuple element is the record field # ms. execNonQuery ("insert into WeiBoUser values ('2', '3')") MS = MSSQL (host = "localhost", user = "sa", pwd = "sa ", db = "MWDatabase") resList = ms. execQuery ("select * from Fiducial_Anchor_Cable") for li in resList: print (li) # local data sqliteimport sqlite3def insert (): conn = sqlite3.connect ('test. db') cursor = conn. cursor () cursor.exe cute ('create table user (id varchar (20) primary key, Name varchar (20) ') cursor.exe cute ('insert into user (id, name) values (\ '1 \', \ 'Michael \ ') cursor. rowcount cursor. close conn. commit () conn. close () def select (): conn = sqlite3.connect ('test. db') cursor = conn. cursor () cursor.exe cute ('select * from user where id =? ', ('1',) values = cursor. fetchall () print (values) cursor. close () conn. close () if _ name __= = '_ main _': xml ()

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.