Convert Python2 code to Python3

Published May 19, 2020, 1:18 p.m.

Got an old code written in python version 2 that you want to convet to python version 3?

There are two primary issues that come from a legacy python 2 code:  The print statement and the raw_input statement.

The following code  can handle both of these issues.  A third issue may come up if you have data written into a pickle file.  That isn't covered here. I may cover it in a follow up tutorial.  Basically you may need to convert your pickle from dos to unix (with a dos2unix program).  And then you may need to change your read/write commands from 'r' to 'rb' and 'w' to 'wb' for the pickle.  This is case and user sensetive so I don't spend time on it here.  This code can be used to change an single file or it can be used on all the files in a directory.

import sys, os

# for one file:
files = [sys.argv[1]]

# for all files
# files = os.listdir(os.getcwd())

pyfiles = [file for file in files if ".py" in file]
# try:
	# pyfiles.remove('convert2to3.py')
# except:
	# pass
print(pyfiles)
for file in pyfiles:
	if "_ORIG" not in file:
		f = open(file, 'r')
		lines  = f.readlines()
		f.close()
		### Preserve the orginal file...
		newfile = file.split(".")[0]+"_ORIG."+file.split(".")[1]
		if newfile not in os.listdir(os.getcwd()):
			f = open(newfile, 'w')
			f.writelines(lines)
			f.close()
		"""
		Need to add parentheses to print( statements and change "input" to "input")
		"""

		for i in range(len(lines)):
			line = lines[i]
			if "print" in line.strip()[:7] and not "print(" in line.replace(' ', ''):	
				line = line.replace("print","print(")
				while"\n" in line[-1]:
					line = line[:-1]
				line += ")\n"
			if "raw_input" in line:
				line = line.replace("raw_input","input")


			lines[i] = line
			
		
		f = open(file, 'w')
		f.writelines(lines)
		f.close()
	else:
		print("preserving the original file...")

I hope this helps.  See you in the next tutorial!

  • Convert Python2 code to Python3
    (currently viewing)