Python | Remove Punctuations From Text File

Punctuations are crazy grammatical symbols which is used in English Language for making written text more readable. But what if for some reason, in your program you need to remove these punctuation symbols from text files. In this article, I’ll discuss about How to use Python Code for removing punctuations from a text file?.

Python Code for Stripping Out Punctuations From Text File

# Python code for removing punctuations from Text File

# Defining a Regex for matching punctuations in strings
punctuations = '''!()-[]{};:'"\,<>./?@#$%^&*_~'''

# Reading in a File containing Text having punctuations
f = open("file.txt", "r")
a_string = f.read()

file_without_punctuation = ""

for char in a_string:
	if char not in punctuations:
		file_without_punctuation = file_without_punctuation + char

# Writing file content without punctuations
new_file = open("file_without_punctuation.txt", "w")
new_file.write(file_without_punctuation)

Input File => file.txt

Output File => output.txt

I hope that this article answered your query, if in case you have some confusion about this. Then let me know down in comments.
Happy Coding 🥳

Leave a Comment