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

Writing nested list to file per line: UnsupportedOperation: not writable

I tried to write a code that removes any line from a file that starts with a number smaller than T and which then writes the remaining lines to another file.

def filter(In,Out, T):
with open(In,'r') as In:
    with open(Out,'r') as Out:
        lines=In.readlines()
        lines=[[e for e in line.split()] for line in lines]
        lines=[line for line in lines if int(line[0])>=T]
        for line in lines:
            for word in line:
                Out.write(f"{word} ")
        return None

    
    

I thought The code would probably write the words in one long line instead of putting it per line but it just returned UnsupportedOperation: not writable and I don’t understand why.

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

>Solution :

it seems like your code had a few bugs

  1. you opened the file for reading with the line with open(Out,'r') as Out: and then tried to write to the file, so I changed the r to w

  2. you tried to open the file for writing when it was already open for reading (you cant open a file while it’s open) so i moved the code the writes back to the file to be after you have finished reading from it

  3. you open the file for reading and gave it the name In but this name is already the name of an argument that you function is getting

this should do the trick:

def filter(In_name,Out, T):
    with open(In_name,'r') as In:        
            lines=In.readlines()
            lines=[[e for e in line.split()] for line in lines]
            lines=[line for line in lines if int(line[0])>=T]
    with open(Out, 'w') as Out:
        for line in lines:
            for word in line:
                Out.write(f"{word} ")
        return None
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