PYTHON

Text Files


Text file handling is a fundamental skill in Python programming. This guide will cover how to open, read, write, and append text files.

 

1. Opening a Text File

To open a text file in Python, use the open() function. This function returns a file object, which allows you to read from or write to the file.

Syntax:

file_object = open(file_name, mode)

 

Common Modes:

  • 'r': Read mode (default). Opens a file for reading.
  • 'w': Write mode. Opens a file for writing (creates a new file or truncates an existing file).
  • 'a': Append mode. Opens a file for appending (creates a new file if it doesn't exist).
  • 't': Text mode (default).

Example:

# Open a file for reading
file = open('example.txt', 'r')
 

 

2. Reading from a Text File

There are several ways to read from a text file in Python:

2.1 read()

Reads the entire file as a single string.

Example:

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

2.2 readline()

Reads one line at a time.

Example:

file = open('example.txt', 'r')
line = file.readline()
while line:
   print(line, end='')  # Avoid adding extra newlines
   line = file.readline()
file.close()
 

2.3 readlines()

Reads all lines and returns them as a list of strings.

Example:

file = open('example.txt', 'r')
lines = file.readlines()
for line in lines:
   print(line, end='')
file.close()
 

 

3. Writing to a Text File

You can write to a text file using the write() and writelines() methods.

3.1 write()

Writes a string to the file.

Example:

file = open('example.txt', 'w')
file.write('Hello, World!\n')
file.write('This is a test.\n')
file.close()
 

3.2 writelines()

Writes a list of strings to the file.

Example:

file = open('example.txt', 'w')
lines = ['Hello, World!\n', 'This is a test.\n']
file.writelines(lines)
file.close()
 

 

4. Appending to a Text File

Appending data to an existing file can be done using the append mode 'a'.

Example:

file = open('example.txt', 'a')
file.write('Appending this line.\n')
file.close()
 

 

 

5. Using the with Statement

Using the with statement for file handling ensures that the file is properly closed after its suite finishes, even if an exception is raised.

Example:

# Reading with `with` statement
with open('example.txt', 'r') as file:
   content = file.read()
   print(content)
# Writing with `with` statement
with open('example.txt', 'w') as file:
   file.write('Hello, World!\n')
   file.write('This is a test.\n')
# Appending with `with` statement
with open('example.txt', 'a') as file:
   file.write('Appending this line.\n')
 

PYTHON