Stats

595 Contributors: 32 Wednesday, April 5, 2017
Licensed under: CC-BY-SA
Not affiliated with Stack Overflow
Rip Tutorial: riptutorial@gmail.com
Roadmap: roadmap

Files & Folders I/O

Introduction

When it comes to storing, reading, or communicating data, working with the files of an operating system is both necessary and easy with Python. Unlike other languages where file input and output requires complex reading and writing objects, Python simplifies the process only needing commands to open, read/write and close the file. This topic explains how Python can interface with files on the operating system.

Syntax

  • file_object = open(filename [, access_mode][, buffering])

Parameters

ParameterDetails
filenamethe path to your file or, if the file is in the working directory, the filename of your file
access_modea string value that determines how the file is opened
bufferingan integer value used for optional line buffering

Remarks

Avoiding the cross-platform Encoding Hell

When using Python's built-in open(), it is best-practice to always pass the encoding argument, if you intend your code to be run cross-platform. The Reason for this, is that a system's default encoding differs from platform to platform.

While linux systems do indeed use utf-8 as default, this is not necessarily true for MAC and Windows.

To check a system's default encoding, try this:

import sys
sys.getdefaultencoding()

from any python interpreter.

Hence, it is wise to always sepcify an encoding, to make sure the strings you're working with are encoded as what you think they are, ensuring cross-platform compatiblity.

with open('somefile.txt', 'r', encoding='UTF-8') as f:
    for line in f:
        print(line)

Related Examples