Files, Folders, I/O

suggest change

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

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)

Feedback about page:

Feedback:
Optional: your email if you want me to get back to you:


Files, Folders, I/O:
* Files, Folders, I/O

Table Of Contents
2 Filter
3 List
7 Loops
15 Files, Folders, I/O
22 Reduce
27 Classes
31 Set
42 Tuple
45 Enum
62 Sockets
89 urllib
92 Idioms
104 Stack
105 Profiling
109 Logging
111 os module
118 Mixins
120 ArcPy
126 Arrays
132 2to3 tool
135 Unicode
138 Neo4j
140 Curses
141 Templates
145 heapq
146 tkinter
154 Audio
155 pyglet
157 ijson
160 Flask
161 Groupby
163 pygame
165 hashlib
166 Gzip
167 ctypes
185 pyaudio
186 shelve