Home > database >  Python - remove spaces on the right side
Python - remove spaces on the right side

Time:04-05

I've text files in folder, but files have data as below:

enter image description here

I don't know how I can remove spaces from right side between CRLF. These are spaces:

33/22-BBB<there is a space to remove>CRLF
import os

root_path = "C:/Users/adm/Desktop/test"

if os.path.exists(root_path):
    files = []
    for name in os.listdir(root_path):
        if os.path.isfile(os.path.join(root_path, name)):
            files.append(os.path.join(root_path, name))

    for ii in files:
        with open(ii) as file:
            for line in file:
                line = line.rstrip()
                if line:
                    print(line)
        file.close()

Does anyone have any idea how to get rid of this?

CodePudding user response:

Those are control characters, change your open() command to:

with open(ii, "r", errors = "ignore") as file:

or

# Bytes mode
with open(ii, "rb") as file:

or

# '\r\n' is CR LF. See link at bottom
with open(ii, "r", newline='\r\n') as file:

Control characters in ASCII

CodePudding user response:

If it is the CRLF characters you would like to remove from each string, you could use line.replace('CRLF', '').

  • Related