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.
CodePudding user response:
it seems like your code had a few bugs
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 ther
tow
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
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