def write_lines(filepath, list_of_strings): with open(filepath, 'w') as fp: for line in list_of_strings: fp.write(line + "\n")
Write List of Strings into File
Write a function that receives a path to a text file as first parameter and
a list of string as second one. The function should write each string in a new
line of the text file. If 5 strings are given in the list, the resulting file
should have 5 lines.
write_lines('test-file.txt', ['hello', 'world'])
test write lines to file - Run Test
import tempfile def test_write_lines_to_file(): fp = tempfile.NamedTemporaryFile(mode="w") write_lines((fp.name), ['my', 'name', 'is', 'john']) with open(fp.name) as fp: assert len(fp.readlines()) == 4 fp.seek(0) assert fp.readlines() == 'is\n'