Reading Files
In Python, reading files is the process of retrieving data from files stored in the system. Think of it like opening a book and reading its contents, Python can open files and access the information within them.
Reading Entire File Content
The simplest way to read a file is to take all its contents at once into memory.
# Reading entire file content at oncef = open('file.txt', 'r')txt = f.read()f.close()print(txt)# Output: [complete file content will be displayed]
This process involves three main steps. First, open the file with the open()
function. Second, read its contents with the read()
method. Third, close the file with the close()
method to free system resources.
Reading File Line by Line
For large files, reading line by line is more efficient because it doesn't load the entire file into memory at once.
# Reading file line by linef = open('file.txt', 'r')for line in f: print(line, end='')f.close()# Note: each line retains its newline character# Parameter end='' prevents adding additional newline
When reading line by line, each line retains the newline character (\n
) at the end. The end=''
parameter in the print()
function prevents adding an additional newline.
Writing to Files
Writing files allows programs to save data or calculation results into files for later use.
Writing Strings to Files
# Writing strings to filef = open('file.txt', 'w')for i in range(1, 11): f.write(f'Line {i}')f.close()# File will contain:# Line 1# Line 2# Line 3# ... (up to Line 10)
Redirecting Print Output to File
You can redirect the output of the print()
function directly to a file using the file
parameter.
# Redirecting print output to filef = open('file.txt', 'w')for i in range(1, 21): print("Line", i, file=f)f.close()# File will contain redirected print output# Line 1# Line 2# ... (up to Line 20)
This method is very useful when you want to save program output results to a file without changing the existing code structure.
File Opening Modes
Python provides various modes for opening files according to the needs of the operations to be performed.
File Opening Syntax
# Basic file opening syntaxf = open('file_name', 'mode')# File operationsf.close()# Examples of various modesf_read = open('data.txt', 'r') # Read only (default)f_write = open('output.txt', 'w') # Write (overwrite if exists)f_append = open('log.txt', 'a') # Append to end of filef_read_write = open('data.txt', 'r+') # Read and write# Don't forget to close filesf_read.close()f_write.close()f_append.close()f_read_write.close()
The mode
parameter determines how the file will be accessed. Mode r
for reading, w
for writing (overwrites old file), a
for appending to the end of file, and r+
for reading and writing.
File Reading Methods
Python provides several methods to read files in different ways according to needs.
read() Method with Parameters
# Various file reading methodsf = open('file.txt', 'r')# Reading n characters from files = f.read(10) # Read first 10 charactersprint("10 characters:", s)# Reading entire filef.seek(0) # Return to beginning of files = f.read() # Read entire fileprint("Entire file:", s)# Reading one line including newlinef.seek(0) # Return to beginning of files = f.readline() # Read one lineprint("One line:", repr(s))f.close()
File Position and Reading
When you open a file, the file position starts from the beginning. Each reading operation advances the file position according to the amount of data read.
# File position demonstrationf = open('sample.txt', 'r')# Initial position at character 0first_read = f.read(5) # Read 5 charactersprint("First read:", first_read)# Position now at character 5second_read = f.read(3) # Read next 3 charactersprint("Second read:", second_read)# Using seek() to set positionf.seek(0) # Return to beginning of filethird_read = f.read(2) # Read 2 characters from startprint("Third read:", third_read)f.close()
Each reading method returns the string that was read. When reaching the end of the file, reading methods return an empty string.
Safe File Handling
Python provides the with
statement for safer and automatic file handling.
# Using with statement for safe file handlingwith open('file.txt', 'r') as f: content = f.read() print(content)# File automatically closed after exiting with block# Writing with with statementwith open('output.txt', 'w') as f: f.write("Hello World!") f.write("Second line")# File automatically closed and saved# Reading and writing simultaneouslywith open('input.txt', 'r') as input_file, open('output.txt', 'w') as output_file: data = input_file.read() output_file.write(data.upper())# Both files automatically closed
The with
statement ensures files are always closed properly, even if an error occurs in the program. This prevents problems like files staying open and consuming system resources.