Python in a Nutshell (IO Tips)

File and Text Operations

1
open(filename, mode='r', bufsize=-1)

File mode

Mode Description
‘r’ The file must already exist, and it is opened in read-only mode.
‘w’ The file is opened in write-only mode. Overwritten or created.
‘a’ The file is opened in write-only mode. Appended or created.
‘r+’ The file must already exist and is opened for both reading and writing.
‘w+’ The file is opened for both reading and writing. Overwritten or created.
‘a+’ The file is opened for both reading and writing.Appended or created.
b Binary.
t Text.

Attributes and Methods of File Objects

1
2
3
4
5
6
7
8
9
10
11
f.close()
f.newlines()
f.read(size=-1)
f.readline(size=-1)
f.readlines(size=-1)
f.seek(pos, how=0)
f.tell( )
f.write(s)
f.writelines(lst)
for line in lst: f.write(line)
for line in f:

The tempfile Module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
# mkstemp(suffix=None, prefix=None, dir=None, text=False)
import tempfile, os
fd, path = tempfile.mkstemp(suffix='.txt', text=True)
try:
    os.close(fd)
    use_filepath(path)
finally:
    os.unlink(path)

# mkdtemp(suffix=None, prefix=None, dir=None)
import tempfile, shutil 
path = tempfile.mkdtemp()
try:
    use_dirpath(path)
finally:
    shutil.rmtree(path)

# TemporaryFile(mode='w+b', bufsize=-1,suffix=None, prefix=None, dir=None)
# NamedTemporaryFile(mode='w+b', bufsize=-1,suffix=None, prefix=None, dir=None)

Compressed Files

The gzip Module

1
2
3
4
5
6
7
8
9
10
11
class GzipFile(filename=None, mode=None, compresslevel=9, fileobj=None)
open(filename, mode='rb', compresslevel=9)
# example
import gzip
underlying_file = open('x.txt.gz', 'wb')
compressing_wrapper = gzip.GzipFile(fileobj=underlying_file, mode='wt') 
# f(compressing_wrapper)
for line in uncompressing_wrapper:
    print line,
compressing_wrapper.close( )
underlying_file.close( )

The bz2 Module

1
2
3
class BZ2File(filename=None, mode='r', buffering=0, compresslevel=9)
compress(s, level=9)
decompress(s)

The tarfile Module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
is_tarfile(filename)
class TarInfo(name='')
t.isdir( )
t.isfile( )
t.issym( )
open(filename, mode='r', fileobj=None, bufsize=10240)
f.add(filepath, arcname=None, recursive=True)
f.addfile(tarinfo, fileobj=None)
f.close( )
f.extract(member, path='.')
f.extractfile(member)
f.getmember(name)
f.getmembers( )
f.getnames( )
f.gettarinfo(name=None, arcname=None, fileobj=None)
f.list(verbose=True)

The zipfile Module

1
2
3
4
5
6
7
8
9
10
11
12
is_zipfile(filename)
class ZipInfo(filename='NoName', date_time=(1980, 1, 1, 0, 0, 0))
class ZipFile(filename, mode='r', compression=zipfile.ZIP_STORED)
z.close( )
z.getinfo(name)
z.infolist( )
z.namelist( )
z.printdir( )
z.read(name)
z.testzip( )
z.write(filename, arcname=None, compress_type=None)
z.writestr(zinfo, bytes)

The zlib Module

1
2
compress(s, level=6)
decompress(s)

The os Module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
access(path, mode)
chdir(path)
chmod(path, mode)
getcwd( )
listdir(path)
makedirs(path, mode=0777) # Good 
mkdir(path, mode=0777)
remove(path)
unlink(path)
removedirs(path)
rename(source, dest)
renames(source, dest)
rmdir(path)
walk(top, topdown=True, onerror=None)

The os.path Module

1
2
3
4
5
6
7
8
9
10
11
12
13
14
15
16
17
18
19
20
21
22
abspath(path)
os.path.normpath(os.path.join(os.getcwd(), path))
basename(path)
os.path.split(path)[1]
>>> os.path.split('b/c/d.e')
('b/c', 'd.e')
>>> os.path.basename('b/c/d.e')
'd.e'
dirname(path)
exists(path)
getatime(path)
getmtime(path)
getsize(path)
isabs(path)
isfile(path)
isdir(path)
islink(path)
join(path, *paths)
>>> print os.path.join('a/b', 'c/d', 'e/f')
a/b/c/d/e/f
>>> print os.path.join('a/b', '/c/d', 'e/f')
/c/d/e/f

The shutil Module

1
2
3
4
5
6
7
copy(src, dst)
copy2(src, dst)
copyfile(src, dst)
copyfileobj(fsrc, fdst, bufsize=16384)
copytree(src, dst, symlinks=False)
move(src, dst)
rmtree(path, ignore_errors=False, onerror=None)

The locale Module

1
2
3
4
5
atof(s)
atoi(s)
format(fmt, num, grouping=False)
str(num)
locale.format('%f', num).