Reading and Writing Text Files

Writing text files

In order to write a text file you need to use do the following steps:

First to create a new file you need to use the built-in function open(). The open function accepts the file name and mode w as the parameters. You can pass therelative or absolute path to the open() function. If you pass a relative path, the file in the current working directory is processed. Mode w indicates that the file is created if it does not exist otherwise the file content will be erased. The open() function returns a file object to allow to have further manipulation.

Second to write text into a text file you method write() of the file object. You can write a single line or multiple lines of texts as a string into a text file. To write a new line to a file you need explicitly add end-of-line character \n to string.

Third, you must close the file to finalize file contents and free up system resources by using method close() of the file object.

In this example, we will create a simple text file into a folder C:\temp. If you do not have this folder in your PC, please go ahead and create one. Here is the code sample to write a text file:

1

2

3

4

5

6

7

8

file_path='C:\\temp\\sample.txt'

file=open(file_path,"w")

file.write('This is a writing text file demo.')

file.write('you can add end-of-line character\n So this is a new line\n')

file.write("""Anotherwaytomakeanewline

inPythonbyusingtriplequotes""")

file.close()

Note that backslash is a special character in Python so you must double up to escape any backslash in a path.

Reading text files

There are several ways to read from text files however, it must follow the below steps:

First you use function open() to open file as in writing file process except you pass mode r to the function to specify that you use the read mode.

Second you can read entire file content into memory by using readlines() method or read line by line in each request by using file operator.

Third you use method close() to close the free up system resources.

In this example, we will use the same file c:\temp\sample.txt we created above to read the whole content in memory and process it. Here is the code sample:

1

2

3

4

5

file_path='C:\\temp\\sample.txt'

file=open(file_path,"r")

forlineinfile.readlines():

print(line)

file.close()

If the text file is large, you can use file iterator instead. The file iterator is designed to read just one more line per request in a loop. Here is an example of using file iterator to read text file: