Python offers you a bunch of amazing functionalities to import data from text files.
One of them is “with” keyword which can be used to open text file to obtain data.
The with statement in Python is used to open a file and create a context in which the file will be used. The main advantage of using with to open a file is that it automatically takes care of closing the file, even if an exception occurs during the processing of the file.
Let’s see an example on how to use it,
with open('file.txt', 'r') as file: data = file.read() print(data)
In above example, the open function is used to open the file ‘file.txt’ in read mode (‘r’). The file is then processed within the with statement, after which the file is automatically closed, even if an exception occurs. The data read from the file is stored in the data variable and can be processed as needed.
The important point to remember is that ‘file.txt’ represents the path of the file.
If your file is on desktop then your code will be
with open('desktop/file.txt', 'r') as file: data = file.read() print(data)