Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

How to optimize reading and cleaning file?

I have a file, which contains strings separated by spaces, tabs and carriage return:

one     two

    three

         four

I’m trying to remove all spaces, tabs and carriage return:

def txt_cleaning(fname):
    with open(fname) as f: 
    new_txt = []
        fname = f.readline().strip()
        new_txt += [line.split() for line in f.readlines()]
    return new_txt

Output:

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

[['one'], ['two'], [], ['three'], [], ['four']]

Expecting, without importing libraries:

['one', 'two', 'three', 'four']

>Solution :

def txt_cleaning(fname):
    new_text = []
    with open(fname) as f:
        for line in f.readlines():
            new_text += [s.strip() for s in line.split() if s]
    return new_text

Or

def txt_cleaning(fname):
    with open(fname) as f:
        return [word.strip() for word in f.read().split() if word]
Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading