How to Split a File into a List in Python

Published on Aug. 22, 2023, 12:15 p.m.

To split a file into a list in Python, you can use the readlines() method to read the file and split it into a list of lines. Here’s an example:

with open('file.txt', 'r') as f:
  lines = f.readlines()

In this example, we use the with statement to open the file ‘file.txt’ in read mode and assign it to the variable f. We then use the readlines() method to read the contents of the file as a list of lines and assign it to the variable lines. Finally, we close the file implicitly when the with block exits.

You can then manipulate the list of lines in various ways, depending on your use case. For example, you can iterate over the lines to process them one by one, or join them back together into a single string using the join() method.

Tags: