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, needing only commands to open, read or 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(), pass the encoding argument if the code should behave the same across platforms. Text mode otherwise uses the locale encoding, or UTF-8 when UTF-8 mode is enabled.

Linux and macOS locales are usually UTF-8. A Windows locale often uses a legacy code page such as cp1252.

locale.getencoding() reports that locale encoding. sys.getdefaultencoding() does not: it is the encoding used by str.encode() when you omit one, and it is UTF-8.

import locale
locale.getencoding()

Pass encoding so the strings you read and write are the encoding you expect:

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:



Table Of Contents