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.
|filename||the path to your file or, if the file is in the working directory, the filename of your file|
|access_mode||a string value that determines how the file is opened|
|buffering||an integer value used for optional line buffering|
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.
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)