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

Question:

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.

Asked By: mister entername

||

Answers:

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
Answered By: Ohad Sharet
Categories: questions Tags: , ,
Answers are sorted by their score. The answer accepted by the question owner as the best is marked with
at the top-right corner.