Python Forum

Full Version: removing tabs from input text
You're currently viewing a stripped down version of our content. View the full version with proper formatting.
Hi, was wondering if you could help. My file f contains some tabs and I want to remove them. I have a code below that does read text line by line but does not remove tabs.
I have something like:
0 0 1 1
1 1 0 0
I want:
0011
1100
Thank you!

def readFromFile(f):

    input_j = list()

    with open(f) as file:

        for line in file:

            input_j.append(list(line.rstrip()))
text = text.replace('\t', '')
In CPython desired result can be achieved by following way (gc closes file automagically); returns list of rows where whitespaces are removed:

def read_from_file(f):
    return [''.join(row.rstrip().split()) for row in open(f)] 
Same thing using with:

def read_from_file(f):
    with open(f, 'r', encoding='UTF-8') as obj:
         return [''.join(row.rstrip().split()) for row in obj]
If you do the same on module level, the fd is only closed, when the program ends.
I guess the fd is closed, because it's in the scope of the list comprehension.
After the list comprehension is done, the fd is not accessible from anywhere.
This means it will be garbage collected an hopefully closed.

I like context managers. If you use pathlib.Path('some_file').read_text() a contextmanager in the read_text method is used internally.