Python provides built-in functions for creating, reading, and writing files. Python can handle two types of files:
- 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 a machine-understandable binary format.
This article focuses on opening, reading, writing, and appending text files in Python.
Opening a Text File
In Python, files can be opened using the built-in open() function. No additional modules are required.
File_object = open(r"File_Name","Access_Mode")
Example: Opening text files in different modes using the open() function.
f1 = open("MyFile1.txt", "a")
f2 = open(r"D:\Text\MyFile2.txt", "w+")
Reading a Text File
Python provides three main methods to read a file:
1. Using 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()
Reads a single line from the file as a string. If n is specified, it reads at most n characters, but never more than one line.
File_object.readline([n])
3. Using 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: This example writes data to myfile.txt, then reopens it in r+ mode to demonstrate various read methods before closing the file.
f1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
f1.write("Hello \n")
f1.writelines(L)
f1.close()
f1 = open("myfile.txt", "r+")
print("Output of read():")
print(f1.read())
print()
f1.seek(0)
print("Output of readline():")
print(f1.readline())
print()
f1.seek(0)
print("Output of read(9):")
print(f1.read(9))
print()
f1.seek(0)
print("Output of readline(9):")
print(f1.readline(9))
print()
f1.seek(0)
print("Output of readlines():")
print(f1.readlines())
print()
f1.close()
Output
Output of read():
Hello
This is Delhi
This is Paris
This is LondonOutput of readline():
HelloOutput of read(9):
Hello
ThOutput of readline(9):
HelloOutput of readlines():
['Hello \n', 'This is Delhi \n', 'This is Paris \n', 'This is London \n']
Writing in a Text File
There are two ways to write in a file:
1. Using write()
Inserts the string str1 in a single line in the text file.
File_object.write(str1)
f1 = open("Employees.txt", "w")
for i in range(3):
name = input("Enter the name of the employee: ")
f1.write(name)
f1.write("\n")
f1.close()
print("Data is written into the file.")
Output
Data is written into the file.
2. Using 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]
f1 = open("Employees.txt", "w")
lst = []
for i in range(3):
name = input("Enter the name of the employee: ")
lst.append(name + '\n')
f1.writelines(lst)
f1.close()
print("Data is written into the file.")
Output
Data is written into the file.
Appending in a Text File
Appending allows you to add new data at the end of an existing file without overwriting its current content. Use mode 'a' to open a file for appending.
In this example, "myfile.txt" is written with initial lines, then "Today" is appended, and finally overwritten with "Tomorrow".
f1 = open("myfile.txt", "w")
L = ["This is Delhi \n", "This is Paris \n", "This is London \n"]
f1.writelines(L)
f1.close()
# Append-adds at last
f1 = open("myfile.txt", "a")
f1.write("Today \n")
f1.close()
f1 = open("myfile.txt", "r")
print("Output of Readlines after appending")
print(f1.readlines())
print()
f1.close()
# Write-Overwrites
f1 = open("myfile.txt", "w")
f1.write("Tomorrow \n")
f1.close()
f1 = open("myfile.txt", "r")
print("Output of Readlines after writing")
print(f1.readlines())
print()
f1.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']
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()
f1 = open("MyFile.txt","a")
f1.close()