pu71n@pu71n.github.io:/$ cat Python - Files

A file has two key properties : a filename (usually written as one word) and a path. The path specifies the location of a file on the computer.

The Current Working Directory

You can git the current working directory as a string value with the os.getcwd() function and change it with os.chdir().

Absolute vs Relative Paths

There are two ways to specify a file path:

  1. An absolute path, which always begins with the root folder.
  2. A relative path, which is relative to the program’s current working directory.

There are also the dot (.) and dot-dot folders. These are not real folders but special names that can be used in a path. A single period (“dot”) for a folder name is shorthand for “this directory”. Two periods (“dot-dot”) means “the parent folder”.

Creating New Folders with os.makedirs()

You can create new folders (directories) with the os.makedirs() function. For example : — >>> import os >>> os.makedirs(‘/home/pu71n/test’) —

The os.path Module

Finding File Sizes and Folder Contents

Once you have ways of handling file paths, you can then start gathering information about specific files and folders. The os.path module provides functions for finding the size of a file in bytes and the files and folders inside a given folder.

Checking Path Validity

Many Python functions will crash with an error if you supply them with a path that does not exist. Ths os.path module provides functions to check whether a given path exists and whether is is a file or folder.

The File Reading/Writing Process

There are three steps to reading or writing files in Python :

  1. Call the open() function to return a File object.
  2. Call the read() or write() method on the File object.
  3. Close the file by calling the close() method on the File object.

####Opening Files with the open() Function To open a file with the open() function, you pass it a string path indicating the file you want to open; it can be either an absolute or realtive path. The open() function returns a File object. This command will open the file in ‘reading plaintext’ mode, or read mode for short. when a file is opened in read mode, Python lets you only read data from the file; you can’t write or modify it in any way. Read mode is the default mode for files you open un Python. The call to open() returns a File object. Now whenever you want to read from or write to the file, you can do so by calling methods on the File object.

Reading the Contents of Files

Now that you have a File object, you can start reading from it. If you want to read the entire contents of a file as a string value, use the File object’s read() method. Alternatively, you can use the readlines() method to get a list of string values from the file, one string for each line of the text which ends with a newline character (\n), except for the last line of the file.

Writing to Files

Python allows you to write contents to a file in a way similar to how the print() function “writes” strings to the screen. You can’t write to a file you’ve opened in read mode, though. Instead, you need to open it in “write plaintext” mode or “append plaintext” mode, or write mode and append mode for short. Write mode will overwrite a variable’s value with a new value. PAss ‘w’ as the second argument to open() to open the file in write mode. Append mode, on the other hand, will append text to the end of the existing file. You can think of this as appending to a list in a variable, rather than overwriting the variable altogether. Pass ‘a’ as the second argument to open() to open the file in append mode. If the filename passed to open() does not exist, both write and append mode will create a new, blank file. After reading or writing a file, call the close() method before opening the file again.

Saving Variables with the shelve Module

You can save variables in your Python programs to binary shelf files using the shelve module. This way, your program can restore data to variables from the hard drive. The shelve modulewill let you add Save and Open features to your program. For example, if you ran a program and entered some configuration settings, you could save those settings to a shelf file and then have the program load them the next time it is run. Here’s an example :


>>> import shelve >>> shelfFile = shelve.open(‘mydata’) >>> cats = [‘Zophie’,’Pooka’,’Simon’] >>> shelfFile[‘cats’] = cats >>> shelfFile.close()


To read and write data using the shelve module, you first import shelve. Call shelve.open() and pass it a filename, and then store the returned shelf value in a variable. You can make changes to the shelf value as if it were a dictionary. When you’re done, call close() on the shelf value. Here, our shelf value is stored in shelfFile. We create a list cats and write shelfFile[‘cats’] = cats to store the list in shelfFile as a value associated with the key ‘cats’ (like in a dictionary). Then we call close() on a shelfFile. After running the previous code, you’ll see a new file in the current working directory. These binary files contain the data you stored in your shelf. Your programs can use the shelve module to later reopen and retrieve the data from these shelf files. Just like dictionaries, shelf values have keys() and values methods that will return list-like values of the keys and values in the shelf. Since these methods return list-like values instead of true list, you should pass them to the list() function to get them in list form.