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 🥳

Gagan

Hi, there I'm founder of ComputerScienceHub(Started this to bring useful Computer Science information just at one place). Personally I've been doing JavaScript, Python development since 2015(Been long) - Worked upon couple of Web Development Projects, Did some Data Science stuff using Python. Nowadays primarily I work as Freelance JavaScript Developer(Web Developer) and on side-by-side managing team of Computer Science specialists at ComputerScienceHub.io

Leave a Reply

Your email address will not be published. Required fields are marked *

Recent Posts