What is Computer

Module: M1-R5: Information Technology Tools and Network Basics

Chapter: Ch1 Computer Intro

🔹 Introduction to File Functions

Python provides several built-in functions to handle files. These include opening, reading, writing, navigating, and closing files.

🔹 Examples of File Functions
1️⃣ open()

Opens a file in specified mode.

file = open('example.txt', 'w')
file.write("Hello QuiteXams!")
file.close()
2️⃣ close()

Closes the opened file.

file = open('example.txt', 'r')
content = file.read()
file.close()
3️⃣ read()

Reads the entire file content as a string.

file = open('example.txt', 'r')
content = file.read()
print(content)
file.close()

Output:

Hello QuiteXams!
4️⃣ readline()

Reads one line at a time.

file = open('example.txt', 'r')
line = file.readline()
print(line)
file.close()
5️⃣ readlines()

Reads all lines as a list.

file = open('example.txt', 'r')
lines = file.readlines()
print(lines)
file.close()

Output:

['Hello QuiteXams!\n']
6️⃣ write()

Writes a string to the file.

file = open('example.txt', 'w')
file.write("Writing with Python!")
file.close()
7️⃣ writelines()

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()
8️⃣ tell()

Returns the current file cursor position.

file = open('example.txt', 'r')
print(file.tell())
file.read()
print(file.tell())
file.close()
9️⃣ seek()

Moves the file cursor to a specified position.

file = open('example.txt', 'r')
file.seek(0)
print(file.read())
file.close()
✅ Summary
  • Use 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.
  • Always close files or use with open() to avoid resource leaks.
Quick Links