Error:

Open file for reading

f = open('test.txt', 'r')

Open file for writing

f = open('test.txt', 'w')

Open file for appending

f = open('test.txt', 'a+')

Open file for read/write

f = open('test.txt', 'r+')

Expand tilde in the filename

import os
homelib = os.path.expanduser('~/Library') # '/Users/user/Library'

Create temporary file

import tempfile
import os

fd, path = tempfile.mkstemp('foo')
out = os.fdopen(fd, 'r+')

out.write('test')
out.flush()
out.close()
os.remove(path)

Lock file

# https://pypi.python.org/pypi/lockfile

from lockfile import FileLock
lock = FileLock("test.txt")
with lock:
    print lock.path, 'is locked.'

Flush output

f = open('test.txt', 'w')
f.write('test')
f.flush()

Open file by file descriptor

import os
f = os.fdopen(5)

Read all contents of the file

with open('test.txt', 'r') as content_file:
    content = content_file.read()

Read number of bytes from the binary file

with open('/bin/ls', 'rb') as content_file:
    signature = content_file.read(4)

Read one line from the file

with open('test.txt', 'r') as f:
  first_line = f.readline()

Read file line by line

with open('test.txt', 'r') as f:
    for line in f:
        line = line.strip()
        print "--> %s" % line

Write line to file

with open('test.txt', 'a+') as f:
    f.write('append\n')

Write number of bytes to the binary file

with open('test.txt', 'wb') as f:
    f.write(b'\x03\xff\x0d')

Get file creation time

import os, time

created = time.ctime(os.stat('test.txt').st_ctime)

Get file modification time

import os, time

modified = time.ctime(os.stat('test.txt').st_mtime)

Set file modification time

import os
file = 'test.txt'
os.utime(file, (os.stat(file).st_atime, 1385780365))

Set file access time

import os
file = 'test.txt'
os.utime(file, (1385780365, os.stat(file).st_mtime))

Delete the file

import os
os.remove('test.txt')

Copy file

import shutil
shutil.copyfile('test.txt', 'backup.txt')

Move file

import shutil
shutil.move('test.txt', 'backup.txt')
# or move to backup/ directory
shutil.move('test.txt', '/path/to/backup')

Rename file

import os
os.rename('test.txt', 'file.formerly.known.as.test.txt')

Get file's inode

import os
inode = os.stat('file.txt').st_ino

Process all files in the directory

import os
path = '/bin'
for file in os.listdir(path):
    current_file = os.path.join(path, file)
    print "--> %s" % current_file
    # do something useful

Process contents of directory recursively

import os
 
rootDir = '.'
for dirName, subdirList, fileList in os.walk(rootDir):
    print('Directory: [%s]' % dirName)
    for fname in fileList:
        print('\t%s' % fname)

Get list of file matching glob

import glob
txt_files = glob.glob('*.txt') # ['file.txt', …]

Remove directory and its contents

import shutil

shutil.rmtree('/path/to/folder')

Get file extension

import os
ext = os.path.splitext('/path/to/test.txt')[1]
ext # '.txt'

Get file name without extension

import os
name = os.path.splitext('/path/to/test.txt')[0]
name # '/path/to/test'

Get directory name of the path

import os
dir = os.path.dirname('/path/to/test.txt')
dir # '/path/to'

Get file name without directory

import os
file = os.path.basename('/path/to/test.txt')
file # 'test.txt'

Check if path is absolute

import os
os.path.isabs('/usr/local') # True

Check if path is relative

import os
not os.path.isabs('./local') # True

Make path absolute

import os 
abs_path = os.path.abspath('./file.txt')
abs_path # '/Users/user/Projects/CodeGofer/file.txt'

Get last path component

import os
path = '/usr/local/bin/'
os.path.basename(os.path.normpath(path)) # 'bin'

Create path with components

import os
os.path.join('a', 'b', 'c') # 'a/b/c'
components = ['foo', 'bar', 'baz']
os.path.join(*components) # 'foo/bar/baz'

Resolve symlinks in the path

import os
real = os.path.realpath('/etc')
real # '/private/etc'

Normalize path

import os
normalized = os.path.normpath('/usr/local/../bin') # '/usr/bin'

Check if path exists

import os
os.path.exists('/usr') # True

Check if path exists and it's a regular file

import os
os.path.isfile('/usr') # False
os.path.isfile('/bin/ls') # True

Check if path exists and it's a directory

import os
os.path.isdir('/usr') # True
os.path.isdir('/bin/ls') # False

Check if path exists and it's readable

import os
os.access('/bin/ls', os.R_OK) # True

Check if path exists and it's writable

import os
os.access('/bin/ls', os.W_OK) # False

Check if path exists and it's executable

import os
os.access('/bin/ls', os.X_OK) # True

Get file's owner

import os
os.stat('/bin/ls').st_uid # 0

Get file's group

import os
os.stat('/bin/ls').st_gid # 0

Get file's mode

import os
os.stat('/bin/ls').st_mode # 0100755

Set file's owner

import os 
import pwd

path = 'file.txt'
uid = pwd.getpwnam("nobody").pw_uid
os.chown(path, uid, os.stat(path).st_gid)

Set file's group

import os 
import grp

path = 'file.txt'
gid = grp.getgrnam("bin").gr_gid
os.chown(path, os.stat(path).st_uid, gid)

Set file's mode

import os 

os.chmod('file.txt', 0600)

Create symlink

import os
os.symlink('/Users/user', 'MyHome')

Resolve symlink

import os
os.readlink('/etc') # 'private/etc'