Module: M3-R5: Python Programming
Chapter: File Processing
Python provides several built-in functions to handle files. These include opening, reading, writing, navigating, and closing files.
Opens a file in specified mode.
file = open('example.txt', 'w')
file.write("Hello QuiteXams!")
file.close()
Closes the opened file.
file = open('example.txt', 'r')
content = file.read()
file.close()
Reads the entire file content as a string.
file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()
Output:
Hello QuiteXams!
Reads one line at a time.
file = open('example.txt', 'r')
line = file.readline()
print(line)
file.close()
Reads all lines as a list.
file = open('example.txt', 'r')
lines = file.readlines()
print(lines)
file.close()
Output:
['Hello QuiteXams!\n']
Writes a string to the file.
file = open('example.txt', 'w')
file.write("Writing with Python!")
file.close()
Writes a list of strings to the file.
lines = ["Line 1\n", "Line 2\n", "Line 3\n"]
file = open('example.txt', 'w')
file.writelines(lines)
file.close()
Returns the current file cursor position.
file = open('example.txt', 'r')
print(file.tell())
file.read()
print(file.tell())
file.close()
Moves the file cursor to a specified position.
file = open('example.txt', 'r')
file.seek(0)
print(file.read())
file.close()
open() to access a file and close() to release it.read(), readline(), readlines() for reading content.write(), writelines() for writing content.tell() and seek() help manage the file cursor.with open() to avoid resource leaks.