Popular python problems and solutions
Tags: python, python problemsPython is a popular programming language that can be used to conduct almost any project. When you learn python, you may come up with different questions regarding various tasks such as file processing, list, dict usage, database, time, url, et al. In this tutorial, we give clean solutions to some of the most frequently problems you may encounter when you learn python.
-
File related questions
How to check whether a file exists using Python?
How to check whether a path is a file?
How to make sure an directory exist?
How to list all files of a directory in Python?
How to read a file line by line into a list with Python?
How to append a line to file in Python?
How to remove a file in Python?
-
Dictionary Related Questions
How to create a dictionary?
123d = {1:11, 2:22}ord = dict([(1,11), (2,22)])How to add key to a dictionary in Python?
1d[3] = 33Check if a given key already exists in a dictionary
12if 3 in d:print '3 exist'Sort a Python dictionary by value
Use operator
12345678910import operatorx ={1:10,3:12,4:3,2:20,0:5}print x{0: 5, 1: 10, 2: 20, 3: 12, 4: 3}import operatorsorted_x = sorted(x.items(), key=operator.itemgetter(1))print sorted_x[(4, 3), (0, 5), (1, 10), (3, 12), (2, 20)]Use Lambda
1sort_x = sorted(x.items(), key=lambda (k, v): v)how to merge two dictionaries in Python?
123456x = {1:1, 2:2, 3:3}y = {1:2, 2:3, 4:5}z = x.copy()z.update(y)print z{1: 2, 2: 3, 3: 3, 4: 5} -
List Related Questions:
How to check if a list is empty?
123a = []if not a:print"List is empty"12if len(a) == 0:print 'List is empty'What’s the difference between the list methods
append()andextend()?1234x =[1,2,3]x.append([4,5])print(x)1, 2, 3, [4, 5]] -
Time related Questions
How to get current time in python?
123import datetimeprint datetime.datetime.now()2015-07-09 14:01:12.947795How to convert String to time object?
1234from datetime import datetimeobj = datetime.strptime('Jun 1 2015 12:50PM', '%b %d %Y %I:%M%p') -
Database Related questions
How do I connect to a MySQL Database in Python?
Install MySQLdb from http://www.kitebird.com/articles/pydbapi.html, then
Use MySQL Connector/Python from MySQL: http://dev.mysql.com/downloads/connector/python/.1234567891011import MySQLdbdb = MySQLdb.connect(host="hostname", # usually localhost or 127.0.0.1user="user", # your usernamepasswd="111111", # your passworddb="test_db") # name of the data basecur = db.cursor()cur.execute("SELECT * FROM test_table")for row in cur.fetchall():print rowdb.close()
1234567891011121314import mysql.connectordb = mysql.connector.connect(user='user', password='111111',host='127.0.0.1',database='test_db')try:cursor = db.cursor()cursor.execute("""select * from test_table""")for row in cur.fetchall():print rowfinally:db.close()











