Python Operations Summary (connect MySQL, parse txt file)

Source: Internet
Author: User
Tags glob

There was a time when Python was not used, it was a little rusty on its syntax, spent a few hours familiar, during the discovery of a lot of small details are unclear. In order to quickly get started next time, to avoid repeated mistakes, I will use Python in the process of some of the issues in this blog post a summary, the main content related to Python operation MySQL database, and parsing txt text. Note: I am using the python2.7 version.

First, the Import module

In Python's script file, you can import other script files, and reference the methods and parameters, using the keyword import. As follows:

Import Os,glob,sys

Second, the basic grammar

1. Definition of common variables

Python as a scripting language, the definition of the variable is very loose, not for the variable specific declaration of its type, similar to the definition of a variable in a JSP page, directly the variable name = ... Can.

2. Array variable definition

Array variable definitions, followed by the = sign with brackets, the length of the array can be specified in brackets. such as: Phonelist = []. Add a value to the array, using the Append () method of the array, and get the value of the array bit, using: Phonelist[index]. Gets the length of the array, which can be used with the Len (List) method.

3. String variables

The string object contains some private methods, such as splitting a string with some sort of delimiter. Split (';') method; the. Strip ('--) method for removing characters from the first character of the string;

Third, read the database table

1. Introduction of MYSQLDB package. Under Windows, download the exe file for this package, click Install directly, Linux is more troublesome.

The import mysqldb as MDB MySQLdb connects to the MySQL database and is only supported in the 2.x version and is recommended for use with version 2.7.

2. Connect MySQL Database

You need to specify the database server address IP, database user name and secret, the database name to be accessed, and the default character encoding. Such as:

conn = Mdb.connect (' HostIP ', ' root ', ' view ', ' db_test ', charset= ' UTF8 ') means access to HostIP database in Db_test, username root, password view, Set character encoding is UTF8.

3. Use cursors to get each row of database query results

cur = conn.cursor () # defines a cursor first

sql = "Select ..." #定义sql语句

Cur.execute ("Set NAMES UTF8") #设定sql语句中的参数的字符编码是utf8

Cur.execute (SQL) #执行sql查询语句.

4. Get the result data for each row in the query results

rows = Cur.fetchall () #rows是很多行的一个集合

val = row[0] #row is a row in rows. Use loops to get each row.

For a For Loop statement, the child statement must be indented one tab key.

When you exit a loop, the statement is separated by one line from the for statement block. As follows:

For row in rows:

Print (Row[0])


Print ("Out of For Block")


V. Read TXT file

1. File path, as follows:

Path=r ' E:\tmp-excel ' + ' \ \ '

For the last path string with \ End, you need to use the escape character form ' \ \ ', the first \ is the escaped identifier, which means that the next character is the real character.

2, read the file content, need to import OS package and Glob package.

Python uses Os.chdir (path) to get the path object. Then with Glob.glob (' *.txt '), the fuzzy matching file name satisfies the *.txt format of the files and returns the array object of the file name.

Use the FO = Open (FileName) method to read the entire contents of the file, lines = Fo.readlines () reads the contents of the file by line. (PS: Although I end each line with a ' \ R ' character, Python may have the entire file content as a single line, that's what I'm doing.) In order to get the data for each row, I split the entire line with. Split (' \ R ') and then process it.


This time the code is written as follows:

#!/usr/bin/python

#coding =utf-8

#-*-Coding:utf-8-*-

Import Os,glob,sys

Phonelist = []

Path=r ' E:\tmp-excel ' + ' \ \ '

Os.chdir (PATH)

Sumj=0

For fname in Glob.glob (' *.txt '):

Fo=open (fname)

Lines=fo.readlines ()

J=0

Print (fname)

For line in lines:

Line=line.split (' \ R ')

For L in line:

L=l.split (',, ')

Phonelist.append (L[1])

#print (L[1])

J=j+1

Print (j)

Sumj=sumj+j

Print ("Total Phoneno is:", Len (phonelist))

Print ("Total Phoneno is:", SUMJ)


Import MySQLdb as MDB

con = None

I=0

con = mdb.connect (' 192.168.10.31 ', ' ro ', ' VI ', ' Ewan ', charset= ' UTF8 ')

cur = con.cursor ()

Sql= "Select User.phone ..."

Cur.execute ("Set NAMES UTF8")

Cur.execute (SQL)

Rows=cur.fetchall ()

Print ("Total NewUser is:", Len (rows))

For row in rows:

#print (Row[0])

For phone in phonelist:

If Row[0]==phone:

I=i+1

Print ("Phone is:", phone,row[0],row[1])

Break


Print ("Total now phone is:", i)




This article is from the "go it on the Road" blog, be sure to keep this source http://andrewli.blog.51cto.com/7625043/1640517

Python Operations Summary (connect MySQL, parse txt file)

Related Article

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.