Skip to content

Instantly share code, notes, and snippets.

@vpayno
Last active December 24, 2015 17:39
Show Gist options
  • Save vpayno/6837605 to your computer and use it in GitHub Desktop.
Save vpayno/6837605 to your computer and use it in GitHub Desktop.
Python Cheat Sheets - File I/O

Python Cheat Sheets

by Victor Payno

File I/O

Sequential Access

f = open("output.txt", "w") # r w r+ a

f.write(str(item) + "\n")

f.close()

file_data = f.read()

for line in f.xreadline():
  print line
f.close()

with open("file.txt", "r") as line:
  print line
print f.closed
  

Random Access

import struct

format_string = 'i'

record_size = struct.calcsize(format_string)

f = open('data.bin', 'wb')

for n in range(0,100):
  packed_data = struct.pack(format_string, n)
  f.write(packed_data)
  print f.tell()

f.close()

f = open('data.bin', 'rb')

for record_number in [(i + 10) * 4 for i in range(0,10)]:
  f.seek(record_size * record_number)
  buffer_binary = f.read(record_size)
  buffer_text = str(list(struct.unpack(format_string, buffer_binary)))[1:-1]
  print "Record Number:", f.tell(), "\tBinary Data:", buffer_binary, "\tText Data:", buffer_text
  f.seek(0)

f.close()

# Record Number: 164      Binary Data: (          Text Data: 40
# Record Number: 180      Binary Data: ,          Text Data: 44
# Record Number: 196      Binary Data: 0          Text Data: 48
# Record Number: 212      Binary Data: 4          Text Data: 52
# Record Number: 228      Binary Data: 8          Text Data: 56
# Record Number: 244      Binary Data: <          Text Data: 60
# Record Number: 260      Binary Data: @          Text Data: 64
# Record Number: 276      Binary Data: D          Text Data: 68
# Record Number: 292      Binary Data: H          Text Data: 72
# Record Number: 308      Binary Data: L          Text Data: 76

Zip Files

import zipfile

z = zipfile.ZiipFile("file.zip", "r")

for file in z.namelist():
    print "File Name:", file
    data = z.read(file)
    print "\tSize: %d Bytes" % (len(data))


Configuration Files

INI

import ConfigParser

configFile = "~/.appini"

defaultConfig = {
    "ssh.hostname": "login",
    "ssh.username": "user1",
    "ssh.password": "",
    "ssh.privkey: "id_rsa"
}

def getConfig(file, config = {}):
    cp = ConfigParser.ConfigParser()
    cp.read(file)
    nc = config.copy()
    for section in cp.sections():
        key = section.lower()
        for option in cp.options(section):
            value = cp.get(section, option)
            nc[key + "." + option.lower()] = value
    return nc

runningConfig = getConfig(configFile, defaultConfig)

Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment