Here's a Python cheat sheet specifically focusing on working with files
Working With Files
Reading a File : To read the entire content of a file
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() print(lines) |
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: print(line.strip()) |
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.') else: 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: file.write(f'{line}\n') |
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 = source.read() destination.write(content) |
Deleting a File : To safely delete a file if it exists
import os if os.path.exists('filename.txt'): os.remove('filename.txt') print('File deleted.') else: 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 = file.read() # Writing to a binary file with open('copy.jpg', 'wb') as file: file.write(content) |
Kickstart your career with our advanced Python courses! placement support Learn more and enroll now:
https://codefrombasics.com/