-2

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?

danio900409
  • 265
  • 2
  • 6
  • 22
  • Does this answer your question? [How can I remove carriage return from a text file with Python?](https://stackoverflow.com/questions/17658055/how-can-i-remove-carriage-return-from-a-text-file-with-python) – Cow Apr 04 '22 at 12:01
  • 1
    FYI : `file.close()` statement is useless, `with` statement already take care of closing it when you leave the code block. – Titouan L Apr 04 '22 at 12:06
  • Does this answer your question? [How do I trim whitespace?](https://stackoverflow.com/questions/1185524/how-do-i-trim-whitespace) – wovano Apr 04 '22 at 13:58

2 Answers2

0

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

Freddy Mcloughlan
  • 4,129
  • 1
  • 13
  • 29
-2

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