top of page

Ultimate Python Cheat Sheet: Practical Python

Here's a Python cheat sheet specifically focusing on working with files

Ultimate Python Cheat Sheet: Practical Python

Working With Files
  • Reading a File : To read the entire content of a file

with open('filename.txt', 'r') as file:

   content =


  • Writing to a File : To write text to a file, over writing existing content

with open('filename.txt', 'w') as file:

    file.write('Hello, Python!')

  • Appending to a File : To add text to the end of an existing file

with open('filename.txt', 'a') as file:

   file.write('\nAppend this line.')

  • Reading Lines into a List : To read a file line by line into a list

with open('filename.txt', 'r') as file:

   lines = file.readlines()


  •  Iterating Over Each Line in a File: To process each line in a file

with open('filename.txt', 'r') as file:

   for line in file:


  • Checking If a File Exists: To check if a file exists before performing file operations

import os

if os.path.exists('filename.txt'):

   print('File exists.')


   print('File does not exist.')

  • Writing Lists to a File : To write each element of a list to a new line in a file

lines = ['First line', 'Second line', 'Third line']

with open('filename.txt', 'w') as file:

   for line in lines:


  • Using With Blocks for Multiple Files: To work with multiple files simultaneously using with blocks

with open('source.txt', 'r') as source, open('destination.txt', 'w') as destination:

   content =


  • Deleting a File : To safely delete a file if it exists

import os

if os.path.exists('filename.txt'):


   print('File deleted.')


   print('File does not exist.')

  • Reading and Writing Binary Files: To read from and write to a file in binary mode (useful for images, videos, etc.)

# Reading a binary file

with open('image.jpg', 'rb') as file:

   content =

# Writing to a binary file

with open('copy.jpg', 'wb') as file:



bottom of page