Python 2To3 Tool Tutorial | 2To3 Tool In Python Tutorial

Python 2to3 tool is another important parameter used by different programmers in performing different tasks. Learn more about it here.

Python 2to3 tool


filename / directory_name


-f FIX, –fix=FIX

-j PROCESSES, –processes=PROCESSES -x NOFIX, –nofix=NOFIX -l, –list-fixes
-p, –print-function

-v, –verbose



-n, –nobackups

-o OUTPUT_DIR, --output-dir=OUTPUT_DIR
-W, --write-unchanged-files --add-suffix=ADD_SUFFIX


2to3 accepts a list of files or directories which is to be transformed as its argument. The directories are recursively traversed for Python sources.

Option Description

Specify transformations to be applied; default: all. List available transformations with –list-fixes

Run 2to3 concurrently

Exclude a transformation

List available transformations

Change the grammar so that print() is considered a function More verbose output
Do not output diffs of the refactoring

Write back modified files

Do not create backups of modified files

Place output files in this directory instead of overwriting input files. Requires the -n flag, as backup files are unnecessary when the input files are not modified.

Write output files even is no changes were required. Useful with -o so that a complete source tree is translated and copied. Implies -w.

Specify a string to be appended to all output filenames. Requires -n if non-empty. Ex.: --add-suffix='3' will generate .py3 files.

Basic Usage

Consider the following Python2.x code. Save the file as

Python 2.x Version ≥ 2.0

def greet(name):
print "Hello, {0}!".format(name)
print "What's your name?"
name = raw_input()

In the above file, there are several incompatible lines. The raw_input() method has been replaced with input() in Python 3.x and print is no longer a statement, but a function. This code can be converted to Python 3.x code using the 2to3 tool.

$ 2to3



Running the above code will output the differences against the original source file as shown below.

RefactoringTool: Skipping implicit fixer: buffer
RefactoringTool: Skipping implicit fixer: idioms
RefactoringTool: Skipping implicit fixer: set_literal
RefactoringTool: Skipping implicit fixer: ws_comma
RefactoringTool: Refactored
--- (original)
+++ (refactored)
@@ -1,5 +1,5 @@
def greet(name):
print "Hello, {0}!".format(name) -print "What's your name?"
-name = raw_input()
print("Hello, {0}!".format(name)) +print("What's your name?")
+name = input() greet(name)
RefactoringTool: Files that need to be modified:
The modifications can be written back to the source file using the -w flag. A backup of the original file called is created, unless the -n flag is given.


$ 2to3 -w


path/to/ -w

Now the file has been converted from Python 2.x to Python 3.x code.

Once finished, will contain the following valid Python3.x code:

Python 3.x Version ≥ 3.0

def greet(name):
print("Hello, {0}!".format(name))
print("What's your name?")
name = input()

Learn more

Leave a Comment