Fundamentals 15 min read

Python File I/O, CSV Handling, and Data Serialization Tutorial

This tutorial explains Python's file opening and closing methods, various file path formats, reading and writing techniques including with‑open, pointer manipulation, copying files, CSV read/write operations, in‑memory streams with StringIO/BytesIO, sys.stdin/stdout usage, and data serialization/deserialization using JSON and pickle.

Python Programming Learning Circle
Python Programming Learning Circle
Python Programming Learning Circle
Python File I/O, CSV Handling, and Data Serialization Tutorial

This article provides a comprehensive guide to file operations in Python, covering the built‑in open() function, file handles, encoding, and mode options.

It explains absolute and relative paths, three ways to write path strings, and the advantages of using with open() for automatic resource management.

Common file access modes are listed ( r , w , a , binary modes rb , wb , ab , and combined modes r+ , w+ , a+ ), along with examples of reading the whole file, reading a specific number of characters, readline() , readlines() , and iterating over lines.

Pointer positioning methods tell() and seek(offset, whence) are demonstrated with examples.

A file‑copy utility is presented using os.path and binary reads/writes in a loop.

CSV handling is described: the format, writing with csv.writer (both writerow and writerows ), and reading with csv.reader .

In‑memory streams are introduced via StringIO for text and BytesIO for binary data, showing how to write and retrieve contents.

Standard I/O redirection using the sys module is shown for stdin , stdout , and stderr , including examples of capturing user input and redirecting output to files.

Data serialization concepts are explained, contrasting JSON (text‑based) and pickle (binary). Examples illustrate json.dumps , json.dump , json.loads , json.load , as well as pickle.dumps , pickle.dump , pickle.loads , and pickle.load , with notes on custom object encoding.

The differences between JSON and pickle are summarized, highlighting portability, supported data types, and use‑case considerations.

pythonSerializationJSONCSVPicklefile-io
Python Programming Learning Circle
Written by

Python Programming Learning Circle

A global community of Chinese Python developers offering technical articles, columns, original video tutorials, and problem sets. Topics include web full‑stack development, web scraping, data analysis, natural language processing, image processing, machine learning, automated testing, DevOps automation, and big data.

0 followers
Reader feedback

How this landed with the community

login Sign in to like

Rate this article

Was this worth your time?

Sign in to rate
Discussion

0 Comments

Thoughtful readers leave field notes, pushback, and hard-won operational detail here.