Tag: python
open file python
In this short tutorial you will learn how to create a file dialog and load its file contents. The file dialog is needed in many applications that use file access.
Related course:
File Dialog Example
To get a filename (not file data) in PyQT you can use the line:
filename = QFileDialog.getOpenFileName(w, 'Open File', '/') |
If you are on Microsoft Windows use
filename = QFileDialog.getOpenFileName(w, 'Open File', 'C:\') |
An example below (includes loading file data):
#! /usr/bin/env python |
Result (output may vary depending on your operating system):

Download PyQT Code (Bulk Collection)
progressbar python
In this article we will demonstrate how to use the progressbar widget. The progressbar is different from the other widgets in that it updates in time.
Related course:
QT4 Progressbar Example
Let’s start with the code:
#! /usr/bin/env python |
The instance bar (of class QProgBar) is used to hold the value of the progressbar. We call the function setValue() to update its value. The parameter w is given to attach it to the main window. We then move it to position (0,20) on the screen and give it a width and height.
To update the progressbar in time we need a QTimer(). We connect the widget with the timer, which calls the function increaseValue(). We set the timer to repeat the function call every 400 milliseconds. You also see the words SLOT and SIGNAL. If a user does an action such as clicking on a button, typing text in a box - the widget sends out a signal. This signal does nothing, but it can be used to connect with a slot, that acts as a receiver and acts on it.
We then connect a pyqtslot to the timeout event.
Result:

Download PyQT Code (Bulk Collection)
python browser
snake ai
In this article we will show you how to create basic game AI (Artificial Intelligence). This article will describe an AI for the game snake.
In this game (snake) both the computer and you play a snake, and the computer snake tries to catch you. In short: the opponent AI tries to determine and go to the destination point based on your location on the board.
You may like
Adding the computer player:
We extend the code with a new class called Computer which will be our computer player. This contains routines to draw and move the computer snake.
class Computer: |
We then call the update and drawing method of the computer.
def on_loop(self): |
This will make the computer snake move and be drawn on the screen. It has the same properties as the human player.
You may like
Adding the intelligence to the computer player
Because this is a simple game, we do not need to create a complete thinking machine inside the game. We simply need some basic intelligence exhibited by our computer player. Intelligence in games is often quite limited because most of the time more complexity is not neccesary or there simply is not the time available to implement clever algorithms.
The algorithm we will add will simply go to the destination. It will neglect any obstacles (the human player).
def target(self,dx,dy): |
Complete code
We end up with this complete code:
from pygame.locals import * |

You may like
Conclusion
You learned how to create a basic computer player using an very simple AI algorithm.
Next: Learn basic sidescroller logic
python ftp client
This article will show you how to use the File Transfer Protocol (FTP) with Python from a client side perspective. We use ftplib, a library that implements the FTP protocol. Using FTP we can create and access remote files through function calls.
Related course
Python Programming Bootcamp: Go from zero to hero
Directory listing
FTP is a protocol for transferring files between systems over a TCP network. It was first developed in 1971 and has since been widely adopted as an effective way to share large files over the internet. File Transfer Protocol (often abbreviated FTP) is an application- layer protocol.
We can list the root directory using this little snippet:
import ftplib |
This will output the directory contents. in a simple console style output. If you want to show a specific directory you must change the directory after connecting with the ftp.cwd(‘/‘) function where the parameter is the directory you want to change to.
import ftplib |
Download file
To download a file we use the retrbinary() function. An example below:
import ftplib |
Uploading files
We can upload files using the storlines() command. This will upload the file README.nluug in the main directory. If you want to upload in another directory combine it with the cwd() function.
import ftplib |
Related course
Python Programming Bootcamp: Go from zero to hero
Other functions
For other functions please refer to the official library documentation.
python snake game
pygame
Pygame Python
Welcome to the first tutorial of the series: Building games with Pygame. Games you create with Pygame can be run on any machine that supports Python, including Windows, Linux and Mac OS.
In this tutorial we will explain the fundamental of building a game with Pygame. We’ll start of with the basics and will teach you how to create the basic framework. In the next tutorials you will learn how to make certain types of games.
You may like
Create Space Invaders with Python
PyGame introduction
You’ll end up with a program similar to the one on the right:
A game always starts in an order similar to this (pseudo code):
initialize() |
The game starts with initialization. All graphics are loaded, sounds are loaded, levels are loaded and any data that needs to be loaded. The game continues running until it receives a quit event. In this game loop we update the game, get input and update the screen. Depending on the game the implementation widely varies, but this fundamental structure is common in all games.
In Pygame we define this as:
import pygame |
The Pygame program starts with the constructor init(). Once that is finished on_execute() is called. This method runs the game: it updates the events, updates the screen. Finally, the game is deinitialized using on_cleanup().
In the initialiasation phase we set the screen resolution and start the Pygame library:
def on_init(self): |
We also load the image.
self._image_surf = pygame.image.load("pygame.png").convert() |
This does not draw the image to the screen, that occurs in on_render().
def on_render(self): |
The blit method draws the image (image_surf) to the coordinate (x,y). In Pygame the coordinates start from (0,0) top left to (wind0wWidth, windowHeight). The method call pygame.display.flip() updates the screen.
You may like
Create Space Invaders with Python
Continue the next tutorial and learn how to add game logic and build games :-)
python chrome extension
face detection python
In this tutorial you will learn how to apply face detection with Python. As input video we will use a Google Hangouts video. There are tons of Google Hangouts videos around the web and in these videos the face is usually large enough for the software to detect the faces.
Detection of faces is achieved using the OpenCV (Open Computer Vision) library. The most common face detection method is to extract cascades. This technique is known to work well with face detection. You need to have the cascade files (included in OpenCV) in the same directory as your program.
Related course
Master Computer Vision with OpenCV and Python
Video with Python OpenCV
To analyse the input video we extract each frame. Each frame is shown for a brief period of time. Start with this basic program:
#! /usr/bin/python |
Upon execution you will see the video played without sound. (OpenCV does not support sound). Inside the while loop we have every video frame inside the variable frame.
Face detection with OpenCV
We will display a rectangle on top of the face. To avoid flickering of the rectangle, we will show it at it latest known position if the face is not detected.
#! /usr/bin/python |
In this program we simply assumed there is one face in the video screen. We reduced the size of the screen to speed up the processing time. This is fine in most cases because detection will work fine in lower resolutions. If you want to execute the face detection in “real time”, keeping the computational cycle short is mandatory. An alternative to this implementation is to process first and display later.
A limitation of this technique is that it does not always detect faces and faces that are very small or occluded may not be detected. It may show false positives such as a bag detected as face. This technique works quite well on certain type of input videos.
Download Computer Vision Examples and Course
Car tracking with cascades

In this tutorial we will look at vehicle tracking using haar features. We have a haar cascade file trained on cars.
The program will detect regions of interest, classify them as cars and show rectangles around them.
Related course:
Master Computer Vision with OpenCV
Detecting with cascades
Lets start with the basic cascade detection program:
#! /usr/bin/python |
This will detect cars in the screen but also noise and the screen will be jittering sometimes. To avoid all of these, we have to improve our car tracking algorithm. We decided to come up with a simple solution.
Related course:
Master Computer Vision with OpenCV
Car tracking algorithm
For every frame:
- Detect potential regions of interest
- Filter detected regions based on vertical,horizontal similarity
- If its a new region, add to the collection
- Clear collection every 30 frames
Removing false positives
The mean square error function is used to remove false positives. We compare vertical and horizontal sides of the images. If the difference is to large or to small it cannot be a car.
ROI detection
A car may not be detected in every frame. If a new car is detected, its added to the collection.
We keep this collection for 30 frames, then clear it.
#!/usr/bin/python |
Final notes
The cascades are not rotation invariant, scale and translation invariant. In addition, Detecting vehicles with haar cascades may work reasonably well, but there is gain with other algorithms (salient points).
You may like:
Download Computer Vision Examples + Course
create csv file python
Spreadsheets often export CSV (comma seperated values) files, because they are easy to read and write. A csv file is simply consists of values, commas and newlines. While the file is called ‘comma seperate value’ file, you can use another seperator such as the pipe character.
Related course
Data Analysis with Python Pandas
Create a spreadsheet file (CSV) in Python
Let us create a file in CSV format with Python. We will use the comma character as seperator or delimter.
import csv |
Running this code will give us this fil persons.csv with this content:
Name,Profession |
You can import the persons.csv file in your favorite office program.

Read a spreadsheet file (csv)
If you created a csv file, we can read files row by row with the code below:
import csv |
This will simply show every row as a list:
['Name', 'Profession'] |
Perhaps you want to store that into Python lists. We get the data from the csv file and then store it into Python lists. We skip the header with an if statement because it does not belong in the lists. Full code:
import csv |
Result:
['Derek', 'Steve', 'Paul'] |
Most spreadsheet or office programs can export csv files, so we recommend you to create any type of csv file and play around with it :-)
Related course
Data Analysis with Python Pandas
python regex
Regular expressions are essentially a highly specialized programming language embedded inside Python that empowers you to specify the rules for the set of possible strings that you want to match.
In Python you need the re module for regular expressions usage. The grammar overview is on the bottom of this page.
Related course:
Python Programming Bootcamp: Go from zero to hero
The Match function
The match function is defined as:
re.match(pattern, string) |
The parameters are:
Parameters | Description |
---|---|
pattern | a regular expression |
string | the input string |
#!/usr/bin/python |
Example outputs:
String | Match |
---|---|
12345 | True |
12358 | True |
55555 | True |
123 | False |
123K5 | False |
5555555 | False |
#!/usr/bin/python |
The Search Function
The search function is defined as:
re.search(pattern, string) |
The parameters are:
Parameter | Description |
---|---|
pattern | a regular expression, defines the string to be searched |
string | the search space |
#!/usr/bin/python |
Regular Expression Examples
A few examples of regular expressions:
Example | Regex |
---|---|
IP address | (([2][5][0-5]\.)|([2][0-4][0-9]\.)|([0-1]?[0-9]?[0-9]\.)){3}(([2][5][0-5])|([2][0-4][0-9])|([0-1]?[0-9]?[0-9])) |
[^@][email protected][^@]+\.[^@]+ | |
Date MM/DD/YY | (\d+/\d+/\d+) |
Integer (positive) | (?<![-.])\b[0-9]+\b(?!\.[0-9]) |
Integer | [+-]?(?<!\.)\b[0-9]+\b(?!\.[0-9]) |
Float | (?<=>)\d+.\d+|\d+ |
Hexadecimal | \s–([0-9a-fA-F]+)(?:–)?\s |
Regex | Description |
---|---|
\d | Matches any decimal digit; this is equivalent to the class [0-9] |
\D | Matches any non-digit character; this is equivalent to the class [^0-9]. |
\s | Matches any whitespace character; this is equivalent to the class [ \t\n\r\f\v]. |
\S | Matches any non-whitespace character; this is equivalent to the class [^ \t\n\r\f\v]. |
\w | Matches any alphanumeric character; this is equivalent to the class [a-zA-Z0-9_]. |
\W | Matches any non-alphanumeric character; this is equivalent to the class [^a-zA-Z0-9_]. |
\Z | Matches only at end of string |
[..] | Match single character in brackets |
[^..] | Match any single character not in brackets |
. | Match any character except newline |
$ | Match the end of the string |
* | Match 0 or more repetitions |
+ | 1 or more repetitions |
{m} | Exactly m copies of the previous RE should be matched. |
| | Match A or B. A|B |
? | 0 or 1 repetitions of the preceding RE |
[a-z] | Any lowercase character |
[A-Z] | Any uppercase character |
[a-zA-Z] | Any character |
[0-9] | Any digit |
from sqlalchemy import * |
Execute with:
python tabledef.py |
The ORM created the database file tabledef.py. It will output the SQL query to the screen, in our case it showed:
CREATE TABLE student ( |
Thus, while we defined a class, the ORM created the database table for us. This table is still empty.
Inserting data into the database
The database table is still empty. We can insert data into the database using Python objects. Because we use the SqlAlchemy ORM we do not have to write a single SQL query. We now simply create Python objects that we feed to the ORM. Save the code below as dummy.py
import datetime |
Execute with:
python dummy.py |
The ORM will map the Python objects to a relational database. This means you do not have any direct interaction from your application, you simply interact with objects. If you open the database with SQLiteman or an SQLite database application you’ll find the table has been created:

Query the data
We can query all items of the table using the code below. Note that Python will see every record as a unique object as defined by the Students class. Save the code as demo.py
import datetime |
On execution you will see:
James Boogie |
To select a single object use the filter() method. A demonstration below:
import datetime |
Output:
Eric York |
Finally, if you do not want the ORM the output any of the SQL queries change the create_engine statement to:
engine = create_engine('sqlite:///student.db', echo=False) |
pyqt qml
If you have not done our first PyQT tutorial yet, you should do it, it’s fun! In this tutorial we will use PyQT4 and a user interface markup language, a language that describes the graphical user interfaces and controls .
Related course:
QML and PyQT
An excerpt of user interface markup graphical user interfaces and language code could look like:
Rectangle { |
Essentially the language tells what the interface should look like. The language we will be using is called QML.
QTCreator
Start a programmed called QTCreator. The tutorial will be quite graphical to help you through the whole process. Simply type qtcreator in the terminal or start it from the menu list. This screen should pop up:

Creating a GUI
Press the big New Project button. Select QT Quick Application from the menu below. Finally press Choose on the bottom right.

A new popup will appear:

Type a name and a valid path to save your project. Then press Next. Select QT Quick 2.0 from the menu list. Press Next. Press Finish. Immediately a user interface defined in the QML language will appear.

Like all great programmers we are going to solve things the most lazy way possible. Instead of typing all the QML code by hand we are going to press the Design button that is on the left of the screen. A drag and drop screen should appear now.

We drag an image onto the area and select the source on the right. Save the project. Open a terminal and locate the qml file you just created. Alternatively you could simply copy the code in the edit box and save it to a .qml file. Enter the command:
qmlviewer main.qml |
This will display the windows as defined in the qml file without any functionality. It is simply a viewer for the interface. We then create some code to load this QML definition:
import sys |
Finally we modify the first line main.qml to:
import Qt 4.7 |
Simply because our QtQuick was missing. Running
python run.py |
Will now display our user interface as defined by QML:

All of the code is simply PyQT, so you could add code like in the previous tutorial. These are the two methods to create a graphical interface with PyQT. This method may be more loosely coupled to the code compared to the method of creating a GUI with QT in the previous tutorial. Despite that both are valid methods.
Download PyQT4 Examples (Bulk Collection)
You may like: Application GUI with PyQT4 or the PyQt4 Tutorials
wxpython

The official wxPython site has several screenshots and downloads for these platforms. wxPython is based on wxWidgets.
Related course: Creating GUI Applications with wxPython
Install wxPython
First download and install WxPython, the Python bindings for wxWidgets.sudo apt-get install python-wxgtk2.8 python-wxtools wx2.8-doc wx2.8-examples wx2.8-headers wx2.8-i18n |
Then install a GUI creator called wxglade:
sudo apt-get install wxglade |
Using a GUI builder such as wxGlade will save you a lot of time, regardless of the GUI library you use. You can easily make complex graphical interfaces because you can simply drag and drop.
Creating our first GUI with Python and wxWidgets:
Start wxglade. You will see its user interface:

Press on tiny window on the top left, below the file icon.

Press OK. An empty window will now appear. Press on the tiny [OK] button in the wxGlade panel and press on the frame. The button will now appear. Press on Application in the tree window.

Set the output file in the wxproperties window.

If you look at the window note you can select multiple programming languages and two versions of wxWidgets. Select Python and wxWidgets 2.8. Finally press Generate code. (Do NOT name the file wx.py because the import needs wx, save it as window.py or something else).
Running wxglade code:
Run:
python window.py |
And a window with a button will appear. Pressing the button will not do anything. To start a function when pressing the button, we need to define a so called Callback. This can be as simple as:
def OnButton(self, Event, button_label): |
Finally we bind the button to the callback function using:
self.button_1.Bind(wx.EVT_BUTTON, self.OnButton ) |
Pressing the button will now write a message to the command line. Instead of the boring command line message, we want to show a message box. This can be done using this command:
wx.MessageBox( "This is a message.", "Button pressed."); |
wxPython example code
The full code below:
#!/usr/bin/env python |
Related course: Creating GUI Applications with wxPython
quantum computing python
So we want to make a quantum application with Python, but since we do not own any quantum computer we need to have a simulator first. Simulation will not have the same performance as an actual quantum computer but we will be able to run applications. We have a choice from three simulators: PyQu , QuTip and Qitensor. We decided to pick QuTip as it has a very large code base and as it has the most recent changes. PyQu hasn’t been updated since 2010 and Qitensor since a year or so.
Related course:
Quantum Computing: An Applied Approach
Installing
We use a Unix machine in this tutorial, but you should be fine with any other operating system. Install using:
sudo add-apt-repository ppa:jrjohansson/qutip-releases
sudo apt-get update
sudo apt-get install python-qutip
We then start Python from the command line and type the commands listed below ( >>> ).
$ python |
This indicates that Qutip has been correctly installed.
The Quantum data structure
In quantum systems we need a data structure that is capable of encapsulating the properties of a quantum operator and ket/bra vectors, we use the Qobj data structure for that. In other words, to effectively simulate a quantum application we need to use the appropriate data structure. Consider the example below:
#!/usr/bin/env python |
And execute with:
python quantum.py |
This will output the quantum object:
Quantum object: dims = [[4], [4]], shape = [4, 4], type = oper, isherm = False |
If you want to specify user input yourself you could use:
#!/usr/bin/env python |
This quantum object will simply hold your user given data:
Quantum object: dims = [[5], [1]], shape = [5, 1], type = ket |
Quantum states and operators
A quantum system is not a simple two-level system, it has multiple states. QuTip includes some predefined states and quantum operators which are listed here.
Qubits and operators
We create a Qubit to hold data. Th Qubit is the quantum analogue of the classical bit. Unlike traditional bits, the qubit can be in a superposition of both states at the same time, a property which is fundamental to quantum computing. The code below will create a qubit:
#!/usr/bin/env python |
You can now apply quantum system operators on the qubit:
#!/usr/bin/env python |
Combining qubits
To describe the states of two coupled qubits we need to take the tensor product of the state vectors for each of the system components. Let us try that:
#!/usr/bin/env python |
The output we will get is:
Quantum object: dims = [[2], [1]], shape = [2, 1], type = ket |
Whats next?
We have built some very simply quantum applications using this simple introduction. Perhaps you want to create an actually useful application, if so you could study more about quantum computing and complete the tutorial at http://qutip.org/docs/latest/index.html