Open In App

Reading and Writing to text files in Python

Last Updated : 24 Sep, 2025
Suggest changes
Share
98 Likes
Like
Report

Python provides built-in functions for creating, writing and reading files. Two types of files can be handled in Python, normal text files and binary files (written in binary format, 0s and 1s).

  • Text files: Each line of text is terminated with a special character called EOL (End of Line), which is new line character ('\n') in Python by default.
  • Binary files: There is no terminator for a line and data is stored after converting it into machine-understandable binary format.

This article focuses on opening, closing, reading and writing data in a text file. Here, we will also see how to get Python output in a text file.

Open Text File

It is done using open() function. No module is required to be imported for this function.

File_object = open(r"File_Name","Access_Mode")

Example: Here, file1 is created as an object for MyFile1 and file2 as object for MyFile2.

Python
# Open MyFile1.txt in append mode
file1 = open("MyFile1.txt", "a")

# Open MyFile2.txt in D:\Text with write+ mode
file2 = open(r"D:\Text\MyFile2.txt", "w+")

Also Read: File Mode in Python

Read Text File

There are three ways to read txt file. Let's understand it one by one:

1. Using read()

read(): Returns the read bytes in form of a string. Reads n bytes, if no n specified, reads the entire file.

File_object.read([n])

2. Using readline()

readline(): Reads one line of the file and returns in form of a string. For specified n, reads at most n bytes. However, does not reads more than one line, even if n exceeds the length of the line.

File_object.readline([n])

3. Using readlines()

readlines(): Reads all the lines and return them as each line a string element in a list.

File_object.readlines()

Note: '\n' is treated as a special character of two bytes.

Example: In this example, a file myfile.txt is created in write mode (w) and data is added using write() and writelines(). The file is then reopened in read and append mode (r+) to demonstrate different read operations: read(), readline(), read(n), readline(n) and readlines(). Finally, file is closed.

Python
file1 = open("myfile.txt", "w")  
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]

file1.write("Hello \n")          # write single line
file1.writelines(L)              # write multiple lines
file1.close()                    # close file

file1 = open("myfile.txt", "r+") # reopen file in read+append mode

print("Output of read():")
print(file1.read())              # read whole file
print()

file1.seek(0)                    # move cursor to start
print("Output of readline():")
print(file1.readline())          # read first line
print()

file1.seek(0)
print("Output of read(9):")
print(file1.read(9))             # read first 9 chars
print()

file1.seek(0)
print("Output of readline(9):")
print(file1.readline(9))         # read 9 chars from line
print()

file1.seek(0)
print("Output of readlines():")
print(file1.readlines())         # read all lines as list
print()

file1.close()

Output

Output of read():
Hello
This is Delhi
This is Paris
This is London

Output of readline():
Hello

Output of read(9):
Hello
Th

Output of readline(9):
Hello

Output of readlines():
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']

Write to Text File

There are two ways to write in a file:

1. Using write()

write(): Inserts the string str1 in a single line in the text file.

File_object.write(str1)

Python
file = open("Employees.txt", "w") 

for i in range(3): 
name = input("Enter the name of the employee: ") 
file.write(name) 
file.write("\n") 
	
file.close() 
print("Data is written into the file.") 

Output

Data is written into the file.

2. Using writelines()

writelines(): For a list of string elements, each string is inserted in text file. Used to insert multiple strings at a single time.

File_object.writelines(L) for L = [str1, str2, str3]

Python
file1 = open("Employees.txt", "w") 
lst = [] 
for i in range(3): 
	name = input("Enter the name of the employee: ") 
	lst.append(name + '\n') 
	
file1.writelines(lst) 
file1.close() 
print("Data is written into the file.") 

Output

Data is written into the file.

Append to a File

In this example, a file named "myfile.txt" is initially opened in write mode ("w") to write lines of text. The file is then reopened in append mode ("a") and "Today" is added to existing content. The output after appending is displayed using readlines. Subsequently, file is reopened in write mode, overwriting content with "Tomorrow". Final output after writing is displayed using readlines.

Python
file1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
file1.writelines(L)
file1.close()

# Append-adds at last
file1 = open("myfile.txt", "a")  # append mode
file1.write("Today \n")
file1.close()

file1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(file1.readlines())
print()
file1.close()

# Write-Overwrites
file1 = open("myfile.txt", "w")  # write mode
file1.write("Tomorrow \n")
file1.close()

file1 = open("myfile.txt", "r")
print("Output of Readlines after writing")
print(file1.readlines())
print()
file1.close()

Output

Output of Readlines after appending
['This is Delhi \n', 'This is Paris \n', 'This is London \n', 'Today \n']
Output of Readlines after writing
['Tomorrow \n']

Related Article: File Objects in Python

Closing a Text File

Python close() function closes file and frees memory space acquired by that file. It is used at the time when file is no longer needed or if it is to be opened in a different file mode.

File_object.close()

Python
file1 = open("MyFile.txt","a")
file1.close()

Explore