Python @ DjangoSpin

PyPro #18 Remove comments from a file with Exception Handling

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon
Reading Time: 1 minutes

Remove comments from a file with Exception Handling in Python: Python script to remove comments from a file.

Remove comments from a file with Exception Handling in Python

# Removing comments from a file with Exception Handling
# Write a program to remove all the comments from a file. Create a new file and leave the original untampered. 
# Such an activity is usually performed while creating minified version of a script, to reduce file size.

import sys

# ask for file names
inputFileName = input('Please enter the name of the file you wish to remove comments from: ')
outputFileName = input('Please enter the name of the new file: ')

# open both files
try:
    inputFileHandler = open(inputFileName, 'r')
    outputFileHandler = open(outputFileName, 'w')
except FileNotFoundError:
    print("Please specify a valid file. Ensure that the file is located in the same directory as the script.")
    sys.exit()

    # read the file line by line; write to new file as it is if no comment in line; modify and then write to new file if comment present
# find() returns the position of a character/substring in a string; returns -1 if not found
# line[0: positionOfHash] slices the line till the character just behind the # symbol. In the process, the new line character after the comment is also deleted, so we manually add it here
for line in inputFileHandler.readlines():
    positionOfHash = line.find('#')

    if positionOfHash != -1:
        line = line[0 : positionOfHash]
        line = line + "\n"

    outputFileHandler.write(line)

inputFileHandler.close()
outputFileHandler.close()

# printing a success message
print(outputFileName,"has been created without comments.")


######## END OF PROGRAM ########

# If you are running on an online environment such as repl.it, and don't have a sample file at hand, uncomment the following to create a sample file.

##fileHandler2 = open('dev_script.py', 'w+')
##fileHandler2.write('myInt = 4						# an integer variable\n')
##fileHandler2.write('myString = \"Ethan\"					# a string variable\n\n')
##fileHandler2.write('myList = [1, 2, 3, 4, 5, 6]				# a list variable\n')
##fileHandler2.write('mySet = set(myList)			# creating a set from a list\n')
##fileHandler2.write('myTuple = 2, 3				# creating a tuple without parentheses\n')
##fileHandler2.write('myDict = {1: \'one\', 2: \'two\'}		# creating a dictionary variable')
##fileHandler2.seek(0)
##print(fileHandler2.read())
Try it here.

See also:

Buffer this pageShare on FacebookPrint this pageTweet about this on TwitterShare on Google+Share on LinkedInShare on StumbleUpon

Leave a Reply