liveBook · Manning

Open

As explained in Get Programming: Learn to code with Python

open is Python's built-in function for opening a file and returning a file object.

open is Python’s built-in function for opening a file and creating a file object. Give it a filename string; the file should be in the same folder as the Python program. section 23.3

Open and read a text file

friends_file = open('friends.txt') (names, phones) = read_file(friends_file) print(names) print(phones) friends_file.close() The first line opens friends.txt. The resulting file object is passed to read_file, which reads the data. Close the file when finished. section 23.3

Listing 29.1. Reading a file
def read_text(filename):
    """                                                 #1
    filename: string, name of file to read              #1
    returns: string, contains all file contents         #1
    """                                                 #1
    inFile = open(filename, 'r')                        #2
    line = inFile.read()                                #3
    return line                                         #4

text = read_text("sonnet18.txt")                        #5
print(text)

Compare a reusable function that opens a filename, reads the entire file into a string, returns it, and prints the result. section 29.2

Remember these practical points:

  • Use open(filename, 'r') when explicitly opening a file for reading. section 29.2
  • Test file-reading functions and inspect their returned data before connecting them to other functions. section 23.3

How Get Programming: Learn to code with Python covers it

How deep it goes
Explains filename-based opening, reading modes, file objects, and closing, without treating file handling internals.
Examples
Demonstrates reading friends.txt into names and phone numbers, then reading an entire sonnet into a string.
What you can do after
Apply it to open text files, pass file objects to functions, read contents, and close files after use.
How it connects
Connects file objects with filenames, functions, reading, strings, and close operations.

Also explained in

Compare how 9 books explain open →

Related concepts

This explainer was generated by Manning's knowledge graph from the text of Get Programming: Learn to code with Python. The section links point to the parts of the book it draws on.