When reading the contents of a file, whitespace sometimes can cause us troubles. To remove whitespace from each line when using Python, you can use the Python strip() function.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    stripped_line = line.strip()

When working with files, if you have bad inputs, you can have some headaches. One such situation is if you have unwanted characters or whitespace in your files.

To get rid of whitespace, you can use the Python string strip() function.

strip() removes leading and trailing characters from a string. The strip() function will remove newline characters as well as regular spaces.

Below is an example of how you can read all lines with readlines() and use strip() to remove whitespace from the lines.

myfile = open("example.txt", "r")

lines = myfile.readlines()

for line in lines:
    stripped_line = line.strip()

Hopefully this article has been useful for you to learn how to remove whitespace from the lines of a file using Python.

Categorized in:

Python,

Last Update: March 22, 2024