Files in Python.docx - Files in Python last modified July 6...

This preview shows page 1 - 4 out of 11 pages.

Files in Python last modified July 6, 2020 In this part of the Python programming tutorial, we work with files and standard input and output. We show how to read from a file and write to a file. We briefly introduce the pickle module. Everything in Python is an object. Everything in UNIX is a file. Python open function The open() function is used to open files in Python. open(file, mode='r', buffering=-1, encoding=None, errors=None, newline=None) The file is the name of the file to be opened. The mode indicates how the file is going to be opened: for reading, writing, or appending. The buffering is an optional integer used to set the buffering policy. The encoding is the name of the encoding used to decode or encode the file. The errors is an optional string that specifies how encoding and decoding errors are to be handled. The newline controls the behaviour of the newline character. The file modes are: Mod e Meaning 'r' Reading (default) 'w' Writing 'a' Appending 'b' Binary data '+' Updating (reading and writing) 'x' Exclusive creation, failing if file exists
In the following examples, we use this text file. works.txt Lost Illusions Beatrix Honorine The firm of Nucingen Old Goriot Colonel Chabert Cousin Bette Python with statement Working with files leads often to errors; and therefore, we have to manage possible exceptions. In addition, the file object must be closed when the file object is not needed anymore. The with statement simplifies exception handling by encapsulating common preparation and cleanup tasks. It also automatically closes the opened file. read_width.py #!/usr/bin/env python # read_width.py with open('works.txt', 'r') as f: contents = f.read() print(contents) The example reads the contents of the works.txt file. with open('works.txt', 'r') as f: With the open() function, we open the works.txt file for reading. The file object is aliased as f . The with statement takes care of exceptions and the closing of the opened file. contents = f.read() The read() method reads all the content until the EOF. It returns the data as one big string. Python read function
The read() function reads the specified number of bytes from the file. If the number of bytes is not specified, it reads the whole file. read_data.py #!/usr/bin/env python # read_data.py import sys with open('works.txt', 'r') as f: print(f.read(5)) print(f.read(9)) The code example read five letters from the file and prints them to the console. Then it reads and prints another nine letters. The

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture

  • Left Quote Icon

    Student Picture