The main problem with reading a list from a text file is that the text file may not be in the correct format.
with open('list.txt') as f: lines = f.read().splitlines()
This code opens the file ‘list.txt’ and reads it line by line. The lines are then stored in the variable ‘lines’.
Working with txt files
There are a few ways to work with text files in Python. The simplest way is to open the file in a text editor like Notepad or TextEdit, and write your code inside it.
Another way is to use the built-in file parser in Python. This module lets you read and write text files as if they were Python objects. To use it, you first need to import the module:
Then, you can read a text file like this:
fileinput.read_text( ‘myfile.txt’ )
This will return a string containing the contents of myfile.txt. You can also write text files like this:
fileinput.write_text( ‘myfile.txt’ , ‘Hello world!’ )
Ways to read from txt files
There are a few ways to read from txt files in Python. The simplest way is to use the built-in open() function:
>>> import os >>> file = ‘test.txt’ >>> print(os.open(file))