You can read a multiline file in different ways. Some of them are less verbose than the others and in this tip I will focus on one-line solution materializing the who le input at once. But let's begin with our input file generation:
output_file_name = "/tmp//multiline_file.txt" multiline_text = """A B C D E""" file_to_write = open(output_file_name, 'w') file_to_write.write(multiline_text) file_to_write.close()
To read a file's lines in a single line of code you can use list+open mix, like in this snippet:
lines = list(open(output_file_name, 'r')) assert 'A\n' in lines assert 'B\n' in lines assert 'C\n' in lines assert 'D\n' in lines assert 'E' in lines
But as you can see, every line is returned with the new line separator which may be problematic. The simplest solution would be the use of strip() method:
lines_without_separator = list(map(lambda line: line.strip(), open(output_file_name, 'r'))) assert 'A' in lines_without_separator assert 'B' in lines_without_separator assert 'C' in lines_without_separator assert 'D' in lines_without_separator assert 'E' in lines_without_separator
Unfortunately, the code is much more verbose than in the first solution. Luckily, a better alternative to eliminate the new line separator exists and it uses splitlines() method:
lines_split_lines = open(output_file_name).read().splitlines() assert 'A' in lines_split_lines assert 'B' in lines_split_lines assert 'C' in lines_split_lines assert 'D' in lines_split_lines assert 'E' in lines_split_lines