Home arrow Python arrow Page 4 - File Management in Python

Pickling Data - Python

File management is a basic function, and an important part of many applications. Python makes file management surprisingly easy, especially when compared to other languages. Peyton McCullough explains the basics.

TABLE OF CONTENTS:
  1. File Management in Python
  2. Getting Information on Existing Files
  3. Directories
  4. Pickling Data
  5. Creating In-memory Files
By: Peyton McCullough
Rating: starstarstarstarstar / 108
January 31, 2005

print this article
SEARCH DEV SHED

TOOLS YOU CAN USE

advertisement

 

Using the methods covered in the previous section, it is possible to read strings from files and write strings to files. However, in some situations, you may need to pass other types of data, such as lists, tuples, dictionaries and other objects. In Python, this is possible through a method known as pickling. To pickle data, you would use the "pickle" module included in the standard library.

 

Let's start by pickling a short list of strings and integers: 

import pickle

fileHandle = open ( 'pickleFile.txt', 'w' )

testList = [ 'This', 2, 'is', 1, 'a', 0, 'test.' ]

pickle.dump ( testList, fileHandle )

fileHandle.close() 

Unpickling the data is just as easy: 

import pickle

fileHandle = open ( 'pickleFile.txt' )

testList = pickle.load ( fileHandle )

fileHandle.cloes() 

We can also store more complex data: 

import pickle

fileHandle = open ( 'pickleFile.txt', 'w' )

testList = [ 123, { 'Calories' : 190 }, 'Mr. Anderson', [ 1, 2, 7 ] ]

pickle.dump ( testList, fileHandle )

fileHandle.close()

 

import pickle

fileHandle = open ( 'pickleFile.txt' )

testList = pickle.load ( fileHandle )

fileHandle.close() 

As you can see, pickling is extremely easy to do with Python's "pickle" module. Numeous objects may be stored in files with it. You can also use the "cPickle" module if it is availible to you. It's exactly the same as the "pickle" modue, but it's faster: 

import cPickle

fileHandle = open ( 'pickleFile.txt', 'w' )

cPickle.dump ( 1776, fileHandle )

fileHandle.close() 



 
 
>>> More Python Articles          >>> More By Peyton McCullough
 

blog comments powered by Disqus
escort Bursa Bursa escort Antalya eskort
   

PYTHON ARTICLES

- Python Big Data Company Gets DARPA Funding
- Python 32 Now Available
- Final Alpha for Python 3.2 is Released
- Python 3.1: String Formatting
- Python 3.1: Strings and Quotes
- Python 3.1: Programming Basics and Strings
- Tuples and Other Python Object Types
- The Dictionary Python Object Type
- String and List Python Object Types
- Introducing Python Object Types
- Mobile Programming using PyS60: Advanced UI ...
- Nested Functions in Python
- Python Parameters, Functions and Arguments
- Python Statements and Functions
- Statements and Iterators in Python

Developer Shed Affiliates

 


Dev Shed Tutorial Topics: