Since new_list
is clearly a list of lines, not a filename, you don't need all the stuff with open
ing and read
ing it. And you also can't do saving in a single write
.
But you can do it almost that simply.
You didn't specify whether the lines in new_list
still have their newlines. Let's first assume they do. So, all you have to do is:
def save_file(filename, new_list):
with open(filename, 'w') as f:
f.write(''.join(new_list))
… or …:
def save_file(filename, new_list):
with open(filename, 'w') as f:
f.writelines(new_list)
But your teacher may be expecting something like this:
def save_file(filename, new_list):
with open(filename, 'w') as f:
for line in new_list:
f.write(line)
What if the newlines were stripped off, so we have to add them back? Then things are a bit more complicated the first two ways, but still very easy the third way:
def save_file(filename, new_list):
with open(filename, 'w') as f:
f.write('\n'.join(new_list) + '\n')
def save_file(filename, new_list):
with open(filename, 'w') as f:
f.writelines(line + '\n' for line in new_list)
def save_file(filename, new_list):
with open(filename, 'w') as f:
for line in new_list:
f.write(line + '\n')
Meanwhile, you have not gotten load_file
to work. It's supposed to return a list of lines, but it doesn't return anything (or, rather, it returns None
). print
ing something just prints it out for the user to see, it doesn't store anything for later use.
You want something like this:
def load_file(filename):
lines = []
with open(filename, 'Ur') as f:
for line in f:
lines.append(line)
return lines
However, there's a much simpler way to write this. If you can do for line in f:
, then f
is some kind of iterable. It's almost the same thing as a list—and if you want to make it into an actual list, that's trivial:
def load_file(filename):
with open(filename, 'Ur') as f:
return list(f)