In Python, you don’t need to import a library in order to read and write files. It’s handled natively in the language.The first thing you’ll need to do is use Python’s built-in open function to get a file object.

The open function opens a file. It’s simple. When you use the open function, it returns something called a file object. File objects contain methods and attributes that can be used to collect information about the file you opened. They can also be used to manipulate said file.

Here we open a file and use write function to write some sentences into the the test.txt file.


In [21]:
file = open('test.txt','w') 
 
file.write('Hello World ') 
file.write('This is our new text file ') 
file.write('and this is another line. ') 
file.write('Why? Because we can. ') 
file.close()

There are actually a number of ways to read a text file in Python, not just one. Here we use read function to read the txt file. You could also use number of libraries like pandas to read files of different format.


In [22]:
file = open('test.txt', 'r') 
print (file.read())


Hello World This is our new text file and this is another line. Why? Because we can. 

In [ ]: