Tag Archives: How to open

How to open, read, and write text files in Python

Let’s say that you need to open, read, and write text files in Python. First you can use the open() built-in function to open the file. Once the file is opened you can use the two built-in methods read() and write() to read from the file and to write to the file.

>>> opened_file = open('file.txt')
>>> the_file_content = opened_file.read()
>>> the_file_content
'Hi there! I am a .txt file!'

The opened_file is a file descriptor object. In the above example, the read() method reads the entire content of the file. If you wish, you can read just a portion of the file, as is shown below:

Continue reading