what is the standard file path in python to be opened
Reading and Writing Files
Variables are a fine style to store data while your programme is running, but if you want your information to persist even subsequently your program has finished, you lot need to save it to a file. You tin can recall of a file'southward contents equally a single cord value, potentially gigabytes in size. In this chapter, you will learn how to use Python to create, read, and relieve files on the hard drive.
Files and File Paths
A file has two fundamental properties: a filename (ordinarily written as one give-and-take) and a path . The path specifies the location of a file on the computer. For example, there is a file on my Windows 7 laptop with the filename project.docx in the path C:\Users\asweigart\Documents . The part of the filename after the last menstruum is called the file'southward extension and tells y'all a file's type. project.docx is a Give-and-take document, and Users , asweigart , and Documents all refer to folders (also called directories ). Folders can comprise files and other folders. For example, project.docx is in the Documents folder, which is within the asweigart folder, which is inside the Users folder. Figure eight-1 shows this binder arrangement.
Figure eight-1. A file in a hierarchy of folders
The C:\ part of the path is the root folder , which contains all other folders. On Windows, the root binder is named C:\ and is also called the C: drive . On OS X and Linux, the root folder is / . In this book, I'll be using the Windows-style root folder, C:\ . If you are entering the interactive shell examples on Os X or Linux, enter /
instead.
Additional volumes , such as a DVD drive or USB thumb drive, will appear differently on different operating systems. On Windows, they appear as new, lettered root drives, such as D:\ or Due east:\ . On OS X, they appear as new folders under the /Volumes folder. On Linux, they appear as new folders nether the /mnt ("mount") folder. Besides note that while folder names and filenames are not case sensitive on Windows and Bone Ten, they are case sensitive on Linux.
Backslash on Windows and Forward Slash on Os X and Linux
On Windows, paths are written using backslashes ( \ ) as the separator betwixt folder names. OS Ten and Linux, even so, employ the forrad slash ( / ) equally their path separator. If you want your programs to work on all operating systems, you will have to write your Python scripts to handle both cases.
Fortunately, this is simple to do with the os.path.bring together()
function. If you pass it the string values of individual file and folder names in your path, bone.path.join()
will render a cord with a file path using the correct path separators. Enter the post-obit into the interactive beat:
>>> import os >>> os.path.join('usr', 'bin', 'spam') 'usr\\bin\\spam'
I'm running these interactive shell examples on Windows, so os.path.bring together('usr', 'bin', 'spam')
returned 'usr\\bin\\spam'
. (Notice that the backslashes are doubled because each backslash needs to be escaped by another backslash character.) If I had called this function on OS 10 or Linux, the string would have been 'usr/bin/spam'
.
The os.path.join() function is helpful if you demand to create strings for filenames. These strings will exist passed to several of the file-related functions introduced in this chapter. For example, the following example joins names from a list of filenames to the end of a folder's name:
>>> myFiles = ['accounts.txt', 'details.csv', 'invite.docx'] >>> for filename in myFiles: print(os.path.join('C:\\Users\\asweigart', filename)) C:\Users\asweigart\accounts.txt C:\Users\asweigart\details.csv C:\Users\asweigart\invite.docx
The Electric current Working Directory
Every program that runs on your estimator has a current working directory , or cwd . Whatever filenames or paths that practice not begin with the root binder are assumed to exist under the current working directory. You tin can get the current working directory as a string value with the os.getcwd()
function and change it with os.chdir()
. Enter the post-obit into the interactive shell:
>>> import bone >>> bone.getcwd() 'C:\\Python34' >>> os.chdir('C:\\Windows\\System32') >>> os.getcwd() 'C:\\Windows\\System32'
Here, the current working directory is set to C:\Python34 , so the filename project.docx refers to C:\Python34\project.docx . When we change the electric current working directory to C:\Windows , project.docx is interpreted every bit C:\ Windows\projection.docx .
Python will display an error if you endeavor to change to a directory that does not exist.
>>> os.chdir('C:\\ThisFolderDoesNotExist') Traceback (most recent phone call final): File "<pyshell#xviii>", line 1, in <module> os.chdir('C:\\ThisFolderDoesNotExist') FileNotFoundError: [WinError 2] The system cannot observe the file specified: 'C:\\ThisFolderDoesNotExist'
Notation
While binder is the more modernistic proper noun for directory, note that current working directory (or simply working directory ) is the standard term, not electric current working folder.
Accented vs. Relative Paths
There are ii ways to specify a file path.
-
An absolute path , which e'er begins with the root folder
-
A relative path , which is relative to the plan'due south current working directory
There are likewise the dot (.
) and dot-dot (..
) folders. These are not real folders but special names that can be used in a path. A single catamenia ("dot") for a folder name is shorthand for "this directory." 2 periods ("dot-dot") means "the parent folder."
Figure 8-2 is an example of some folders and files. When the current working directory is set to C:\bacon , the relative paths for the other folders and files are set up as they are in the figure.
Figure eight-2. The relative paths for folders and files in the working directory C:\bacon
The .\ at the outset of a relative path is optional. For example, .\spam.txt and spam.txt refer to the same file.
Creating New Folders with bone.makedirs()
Your programs can create new folders (directories) with the os.makedirs()
function. Enter the following into the interactive shell:
>>> import os >>> os.makedirs('C:\\succulent\\walnut\\waffles')
This will create not merely the C:\delicious folder but likewise a walnut folder inside C:\delicious and a waffles binder inside C:\delicious\walnut . That is, bone.makedirs()
will create any necessary intermediate folders in club to ensure that the full path exists. Effigy 8-iii shows this bureaucracy of folders.
Figure 8-3. The result of os.makedirs('C:\\delicious \\walnut\\waffles')
The os.path Module
The bone.path
module contains many helpful functions related to filenames and file paths. For instance, yous've already used os.path.join()
to build paths in a way that will piece of work on any operating arrangement. Since os.path
is a module inside the bone
module, yous can import information technology by simply running import os
. Whenever your programs need to work with files, folders, or file paths, you can refer to the short examples in this section. The full documentation for the os.path
module is on the Python website at http://docs.python.org/iii/library/os.path.html .
Note
Most of the examples that follow in this section will require the os
module, and then recollect to import it at the get-go of any script you write and whatsoever time you restart IDLE. Otherwise, you'll go a NameError: name 'bone' is not defined
error message.
Handling Absolute and Relative Paths
The os.path
module provides functions for returning the accented path of a relative path and for checking whether a given path is an absolute path.
-
Calling
os.path.abspath(
path
)
volition render a string of the absolute path of the statement. This is an easy way to convert a relative path into an accented one. -
Calling
os.path.isabs(
path
)
will returnTrue
if the argument is an absolute path andFaux
if it is a relative path. -
Calling
os.path.relpath(
path, beginning
)
will return a string of a relative path from thestart
path topath
. Ifstart
is not provided, the electric current working directory is used as the start path.
Try these functions in the interactive shell:
>>> bone.path.abspath('.') 'C:\\Python34' >>> os.path.abspath('.\\Scripts') 'C:\\Python34\\Scripts' >>> os.path.isabs('.') Fake >>> os.path.isabs(os.path.abspath('.')) True
Since C:\Python34 was the working directory when os.path.abspath()
was chosen, the "single-dot" folder represents the accented path 'C:\\Python34'
.
Note
Since your system probably has different files and folders on information technology than mine, you lot won't be able to follow every example in this chapter exactly. Yet, effort to follow along using folders that exist on your computer.
Enter the following calls to os.path.relpath()
into the interactive trounce:
>>> os.path.relpath('C:\\Windows', 'C:\\') 'Windows' >>> os.path.relpath('C:\\Windows', 'C:\\spam\\eggs') '..\\..\\Windows' >>> os.getcwd() 'C:\\Python34'
Calling os.path.dirname(
path
)
will return a cord of everything that comes before the last slash in the path
argument. Calling bone.path.basename(
path
)
volition return a cord of everything that comes later the last slash in the path
argument. The dir name and base name of a path are outlined in Figure viii-four.
Figure 8-four. The base name follows the last slash in a path and is the same as the filename. The dir name is everything before the last slash.
For example, enter the following into the interactive shell:
>>> path = 'C:\\Windows\\System32\\calc.exe' >>> os.path.basename(path) 'calc.exe' >>> os.path.dirname(path) 'C:\\Windows\\System32'
If you need a path's dir proper name and base of operations name together, you can just telephone call os.path.dissever()
to get a tuple value with these two strings, like so:
>>> calcFilePath = 'C:\\Windows\\System32\\calc.exe' >>> os.path.split(calcFilePath) ('C:\\Windows\\System32', 'calc.exe')
Notice that y'all could create the same tuple by calling os.path.dirname()
and os.path.basename()
and placing their return values in a tuple.
>>> (os.path.dirname(calcFilePath), os.path.basename(calcFilePath)) ('C:\\Windows\\System32', 'calc.exe')
But bone.path.separate()
is a nice shortcut if you need both values.
Also, note that bone.path.split()
does not take a file path and render a list of strings of each folder. For that, utilise the divide()
cord method and split on the string in os.sep
. Call up from earlier that the bone.sep
variable is set to the correct binder-separating slash for the computer running the program.
For example, enter the post-obit into the interactive beat out:
>>> calcFilePath.split(os.path.sep) ['C:', 'Windows', 'System32', 'calc.exe']
On Bone Ten and Linux systems, in that location will exist a blank string at the start of the returned listing:
>>> '/usr/bin'.carve up(os.path.sep) ['', 'usr', 'bin']
The split()
cord method will work to return a list of each office of the path. It will work on whatever operating system if you pass it os.path.sep
.
Finding File Sizes and Folder Contents
In one case you lot have means of treatment file paths, y'all can and so 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.
-
Calling
os.path.getsize(
path
)
will render the size in bytes of the file in thepath
argument. -
Calling
bone.listdir(
path
)
will return a list of filename strings for each file in thepath
argument. (Annotation that this function is in theos
module, notos.path
.)
Here's what I get when I endeavor these functions in the interactive trounce:
>>> os.path.getsize('C:\\Windows\\System32\\calc.exe') 776192 >>> bone.listdir('C:\\Windows\\System32') ['0409', '12520437.cpx', '12520850.cpx', '5U877.ax', 'aaclient.dll', -- snip -- 'xwtpdui.dll', 'xwtpw32.dll', 'zh-CN', 'zh-HK', 'zh-TW', 'zipfldr.dll']
Equally you lot can run into, the calc.exe program on my computer is 776,192 bytes in size, and I take a lot of files in C:\Windows\system32 . If I want to notice the total size of all the files in this directory, I can utilise os.path.getsize()
and os.listdir()
together.
>>> totalSize = 0 >>> for filename in bone.listdir('C:\\Windows\\System32'): totalSize = totalSize + os.path.getsize(os.path.join('C:\\Windows\\System32', filename)) >>> print(totalSize) 1117846456
As I loop over each filename in the C:\Windows\System32 binder, the totalSize
variable is incremented by the size of each file. Detect how when I phone call os.path.getsize()
, I apply os.path.bring together()
to join the folder name with the current filename. The integer that os.path.getsize()
returns is added to the value of totalSize
. After looping through all the files, I print totalSize
to see the total size of the C:\Windows\System32 folder.
Checking Path Validity
Many Python functions volition crash with an error if y'all supply them with a path that does not exist. The bone.path
module provides functions to check whether a given path exists and whether information technology is a file or binder.
-
Calling
os.path.exists(
path
)
volition renderTrue
if the file or binder referred to in the argument exists and will returnFalse
if it does not be. -
Calling
os.path.isfile(
path
)
will returnTruthful
if the path argument exists and is a file and will returnSimulated
otherwise. -
Calling
bone.path.isdir(
path
)
will returnTruthful
if the path statement exists and is a folder and volition returnFalse
otherwise.
Hither's what I get when I try these functions in the interactive shell:
>>> os.path.exists('C:\\Windows') True >>> os.path.exists('C:\\some_made_up_folder') Simulated >>> os.path.isdir('C:\\Windows\\System32') True >>> os.path.isfile('C:\\Windows\\System32') False >>> os.path.isdir('C:\\Windows\\System32\\calc.exe') False >>> os.path.isfile('C:\\Windows\\System32\\calc.exe') Truthful
Yous can determine whether at that place is a DVD or wink drive currently attached to the computer by checking for it with the os.path.exists()
office. For instance, if I wanted to check for a flash drive with the volume named D:\ on my Windows computer, I could do that with the following:
>>> bone.path.exists('D:\\') False
Oops! It looks like I forgot to plug in my flash bulldoze.
The File Reading/Writing Process
One time you are comfortable working with folders and relative paths, you'll be able to specify the location of files to read and write. The functions covered in the adjacent few sections volition apply to plaintext files. Plaintext files comprise only bones text characters and do not include font, size, or color information. Text files with the .txt extension or Python script files with the .py extension are examples of plaintext files. These can be opened with Windows'due south Notepad or Bone X'southward TextEdit application. Your programs tin can easily read the contents of plaintext files and treat them as an ordinary string value.
Binary files are all other file types, such as word processing documents, PDFs, images, spreadsheets, and executable programs. If y'all open a binary file in Notepad or TextEdit, it will look like scrambled nonsense, like in Effigy eight-5.
Figure viii-5. The Windows calc.exe
plan opened in Notepad
Since every different type of binary file must be handled in its own way, this book will not go into reading and writing raw binary files directly. Fortunately, many modules make working with binary files easier—yous will explore i of them, the shelve
module, later in this chapter.
There are three steps to reading or writing files in Python.
-
Call the
open()
function to return aFile
object. -
Call the
read()
orwrite()
method on theFile
object. -
Shut the file by calling the
shut()
method on theFile
object.
Opening Files with the open up() Part
To open up a file with the open()
office, you pass it a string path indicating the file you lot want to open up; it can be either an accented or relative path. The open up()
function returns a File
object.
Try it by creating a text file named hello.txt using Notepad or TextEdit. Type Howdy world!
every bit the content of this text file and salve it in your user home folder. Then, if you're using Windows, enter the following into the interactive beat out:
>>> helloFile = open('C:\\Users\\ your_home_folder \\hello.txt')
If you're using OS X, enter the following into the interactive shell instead:
>>> helloFile = open up('/Users/ your_home_folder /how-do-you-do.txt')
Make sure to replace your_home_folder
with your computer username. For example, my username is asweigart , so I'd enter 'C:\\Users\\asweigart\\ hello.txt'
on Windows.
Both these commands will open up the file in "reading plaintext" mode, or read mode for short. When a file is opened in read way, Python lets y'all simply read data from the file; yous tin can't write or modify it in any way. Read way is the default style for files you lot open up in Python. But if you don't desire to rely on Python's defaults, you lot can explicitly specify the mode by passing the string value 'r'
as a second argument to open()
. And so open('/Users/asweigart/ howdy.txt', 'r')
and open up('/Users/asweigart/hello.txt')
practise the same thing.
The phone call to open()
returns a File
object. A File
object represents a file on your figurer; it is just another type of value in Python, much like the lists and dictionaries y'all're already familiar with. In the previous example, you stored the File
object in the variable helloFile
. Now, whenever you want to read from or write to the file, you tin do so by calling methods on the File
object in helloFile
.
Reading the Contents of Files
Now that you lot have a File
object, you tin beginning reading from it. If y'all want to read the entire contents of a file as a string value, use the File
object'south read()
method. Permit's continue with the hello.txt File
object you stored in helloFile
. Enter the following into the interactive shell:
>>> helloContent = helloFile.read() >>> helloContent 'Hello earth!'
If you think of the contents of a file as a single large string value, the read()
method returns the cord that is stored in the file.
Alternatively, you tin can utilize the readlines()
method to become a list of string values from the file, ane cord for each line of text. For example, create a file named sonnet29.txt in the aforementioned directory as hello.txt and write the following text in it:
When, in disgrace with fortune and men's optics, I all lone beweep my outcast state, And trouble deafened sky with my bootless cries, And expect upon myself and curse my fate,
Make sure to carve up the 4 lines with line breaks. And then enter the following into the interactive shell:
>>> sonnetFile = open('sonnet29.txt') >>> sonnetFile.readlines() [When, in disgrace with fortune and men's eyes,\n', ' I all lonely beweep my outcast state,\n', And trouble deaf heaven with my bootless cries,\n', And expect upon myself and curse my fate,']
Note that each of the cord values ends with a newline character, \due north
, except for the last line of the file. A list of strings is often easier to work with than a unmarried large string value.
Writing to Files
Python allows yous to write content to a file in a way similar to how the print()
function "writes" strings to the screen. You lot can't write to a file yous've opened in read mode, though. Instead, yous need to open it in "write plaintext" mode or "suspend plaintext" manner, or write mode and append fashion for short.
Write mode volition overwrite the existing file and start from scratch, just like when y'all overwrite a variable's value with a new value. Laissez passer 'westward'
as the 2nd argument to open()
to open up the file in write fashion. Suspend mode, on the other hand, will suspend text to the end of the existing file. Yous tin can retrieve of this as appending to a list in a variable, rather than overwriting the variable altogether. Laissez passer 'a'
as the 2d statement to open()
to open the file in append mode.
If the filename passed to open up()
does not exist, both write and suspend mode will create a new, blank file. Later reading or writing a file, call the close()
method earlier opening the file again.
Let's put these concepts together. Enter the following into the interactive shell:
>>> baconFile = open('salary.txt', 'west') >>> baconFile.write('Howdy world!\n') 13 >>> baconFile.shut() >>> baconFile = open('bacon.txt', 'a') >>> baconFile.write('Bacon is not a vegetable.') 25 >>> baconFile.close() >>> baconFile = open('salary.txt') >>> content = baconFile.read() >>> baconFile.close() >>> print(content) Hi globe! Bacon is not a vegetable.
First, nosotros open up salary.txt in write manner. Since there isn't a bacon.txt even so, Python creates one. Calling write()
on the opened file and passing write()
the cord statement 'Hi world! /north'
writes the string to the file and returns the number of characters written, including the newline. Then we close the file.
To add text to the existing contents of the file instead of replacing the string we just wrote, we open the file in append mode. Nosotros write 'Salary is not a vegetable.'
to the file and close information technology. Finally, to print the file contents to the screen, nosotros open up the file in its default read style, phone call read()
, store the resulting File
object in content
, close the file, and print content
.
Note that the write()
method does not automatically add a newline character to the end of the string similar the print()
function does. Yous will have to add this character yourself.
Saving Variables with the shelve Module
Yous can save variables in your Python programs to binary shelf files using the shelve
module. This way, your programme tin can restore data to variables from the hard drive. The shelve
module will let you lot add Save and Open features to your program. For example, if you ran a program and entered some configuration settings, you lot could save those settings to a shelf file then accept the programme load them the next time information technology is run.
Enter the following into the interactive shell:
>>> import shelve >>> shelfFile = shelve.open up('mydata') >>> cats = ['Zophie', 'Pooka', 'Simon'] >>> shelfFile['cats'] = cats >>> shelfFile.close()
To read and write information using the shelve
module, you first import shelve
. Call shelve.open()
and pass information technology a filename, and then shop the returned shelf value in a variable. You tin make changes to the shelf value as if it were a dictionary. When you're washed, call close()
on the shelf value. Hither, our shelf value is stored in shelfFile
. Nosotros create a list cats
and write shelfFile['cats'] = cats
to store the list in shelfFile
as a value associated with the key 'cats'
(similar in a dictionary). So nosotros telephone call close()
on shelfFile
.
After running the previous lawmaking on Windows, you will see three new files in the electric current working directory: mydata.bak , mydata.dat , and mydata.dir . On OS X, simply a single mydata.db file will exist created.
These binary files incorporate the data you stored in your shelf. The format of these binary files is non important; you merely need to know what the shelve
module does, non how it does it. The module frees you from worrying about how to store your plan'south data to a file.
Your programs can apply the shelve
module to after reopen and retrieve the information from these shelf files. Shelf values don't have to exist opened in read or write way—they tin can do both once opened. Enter the following into the interactive crush:
>>> shelfFile = shelve.open up('mydata') >>> type(shelfFile) <course 'shelve.DbfilenameShelf'> >>> shelfFile['cats'] ['Zophie', 'Pooka', 'Simon'] >>> shelfFile.shut()
Here, we open the shelf files to check that our data was stored correctly. Entering shelfFile['cats']
returns the aforementioned list that we stored earlier, so we know that the listing is correctly stored, and we telephone call close()
.
Only like dictionaries, shelf values have keys()
and values()
methods that will render list-like values of the keys and values in the shelf. Since these methods render list-like values instead of true lists, you should laissez passer them to the list()
part to go them in listing form. Enter the following into the interactive vanquish:
>>> shelfFile = shelve.open('mydata') >>> listing(shelfFile.keys()) ['cats'] >>> list(shelfFile.values()) [['Zophie', 'Pooka', 'Simon']] >>> shelfFile.shut()
Plaintext is useful for creating files that you lot'll read in a text editor such as Notepad or TextEdit, but if you want to salvage information from your Python programs, utilise the shelve
module.
Saving Variables with the pprint.pformat() Function
Recall from Pretty Printing that the pprint.pprint()
office will "pretty print" the contents of a list or dictionary to the screen, while the pprint.pformat()
function will return this same text equally a string instead of printing information technology. Not but is this string formatted to exist easy to read, just it is likewise syntactically correct Python code. Say you have a lexicon stored in a variable and y'all want to save this variable and its contents for futurity utilise. Using pprint.pformat()
will give you a cord that you can write to .py file. This file will be your very own module that you tin can import whenever you want to use the variable stored in information technology.
For example, enter the post-obit into the interactive beat:
>>> import pprint >>> cats = [{'proper name': 'Zophie', 'desc': 'stubby'}, {'name': 'Pooka', 'desc': 'fluffy'}] >>> pprint.pformat(cats) "[{'desc': 'chubby', 'name': 'Zophie'}, {'desc': 'fluffy', 'proper noun': 'Pooka'}]" >>> fileObj = open('myCats.py', 'due west') >>> fileObj.write('cats = ' + pprint.pformat(cats) + '\northward') 83 >>> fileObj.close()
Here, we import pprint
to allow u.s.a. utilize pprint.pformat()
. We have a list of dictionaries, stored in a variable cats
. To keep the listing in cats
available even after we shut the beat, we use pprint.pformat()
to render information technology as a string. In one case nosotros have the information in cats
equally a cord, it's easy to write the string to a file, which nosotros'll call myCats.py .
The modules that an import
statement imports are themselves just Python scripts. When the cord from pprint.pformat()
is saved to a .py file, the file is a module that can be imported just like any other.
And since Python scripts are themselves just text files with the .py file extension, your Python programs can even generate other Python programs. You can then import these files into scripts.
>>> import myCats >>> myCats.cats [{'name': 'Zophie', 'desc': 'chubby'}, {'proper noun': 'Pooka', 'desc': 'fluffy'}] >>> myCats.cats[0] {'name': 'Zophie', 'desc': 'chubby'} >>> myCats.cats[0]['name'] 'Zophie'
The benefit of creating a .py file (every bit opposed to saving variables with the shelve
module) is that considering it is a text file, the contents of the file can be read and modified by anyone with a uncomplicated text editor. For virtually applications, all the same, saving data using the shelve
module is the preferred way to save variables to a file. Only bones information types such as integers, floats, strings, lists, and dictionaries can be written to a file as simple text. File
objects, for example, cannot be encoded equally text.
Projection: Generating Random Quiz Files
Say you're a geography instructor with 35 students in your course and you desire to give a pop quiz on The states state capitals. Alas, your class has a few bad eggs in it, and y'all can't trust the students not to crook. You'd like to randomize the social club of questions then that each quiz is unique, making it incommunicable for anyone to crib answers from anyone else. Of course, doing this by hand would exist a lengthy and boring affair. Fortunately, you know some Python.
Here is what the program does:
-
Creates 35 different quizzes.
-
Creates 50 multiple-choice questions for each quiz, in random society.
-
Provides the correct reply and three random wrong answers for each question, in random society.
-
Writes the quizzes to 35 text files.
-
Writes the answer keys to 35 text files.
This means the code will need to do the following:
-
Store the states and their capitals in a dictionary.
-
Call
open up()
,write()
, andclose()
for the quiz and answer key text files. -
Use
random.shuffle()
to randomize the lodge of the questions and multiple-choice options.
Step 1: Store the Quiz Data in a Lexicon
The starting time pace is to create a skeleton script and fill it with your quiz information. Create a file named randomQuizGenerator.py , and make it look similar the post-obit:
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random order, along with the respond key. ❶ import random # The quiz data. Keys are states and values are their capitals. ❷ capitals = {'Alabama': 'Montgomery', 'Alaska': 'Juneau', 'Arizona': 'Phoenix', 'Arkansas': 'Piffling Rock', 'California': 'Sacramento', 'Colorado': 'Denver', 'Connecticut': 'Hartford', 'Delaware': 'Dover', 'Florida': 'Tallahassee', 'Georgia': 'Atlanta', 'Hawaii': 'Honolulu', 'Idaho': 'Boise', 'Illinois': 'Springfield', 'Indiana': 'Indianapolis', 'Iowa': 'Des Moines', 'Kansas': 'Topeka', 'Kentucky': 'Frankfort', 'Louisiana': 'Baton Rouge', 'Maine': 'Augusta', 'Maryland': 'Annapolis', 'Massachusetts': 'Boston', 'Michigan': 'Lansing', 'Minnesota': 'Saint Paul', 'Mississippi': 'Jackson', 'Missouri': 'Jefferson City', 'Montana': 'Helena', 'Nebraska': 'Lincoln', 'Nevada': 'Carson City', 'New Hampshire': 'Concord', 'New Bailiwick of jersey': 'Trenton', 'New United mexican states': 'Santa Fe', 'New York': 'Albany', 'North Carolina': 'Raleigh', 'Northward Dakota': 'Bismarck', 'Ohio': 'Columbus', 'Oklahoma': 'Oklahoma Urban center', 'Oregon': 'Salem', 'Pennsylvania': 'Harrisburg', 'Rhode Isle': 'Providence', 'South Carolina': 'Columbia', 'S Dakota': 'Pierre', 'Tennessee': 'Nashville', 'Texas': 'Austin', 'Utah': 'Salt Lake Metropolis', 'Vermont': 'Montpelier', 'Virginia': 'Richmond', 'Washington': 'Olympia', 'West Virginia': 'Charleston', 'Wisconsin': 'Madison', 'Wyoming': 'Cheyenne'} # Generate 35 quiz files. ❸ for quizNum in range(35): # TODO: Create the quiz and answer primal files. # TODO: Write out the header for the quiz. # TODO: Shuffle the society of the states. # TODO: Loop through all fifty states, making a question for each.
Since this program will be randomly ordering the questions and answers, y'all'll need to import the random
module ❶ to brand use of its functions. The capitals
variable ❷ contains a lexicon with U.s.a. states as keys and their capitals as values. And since you want to create 35 quizzes, the code that actually generates the quiz and respond key files (marked with TODO
comments for now) will go inside a for
loop that loops 35 times ❸. (This number can exist changed to generate any number of quiz files.)
Step ii: Create the Quiz File and Shuffle the Question Society
Now it's time to beginning filling in those TODO
due south.
The code in the loop volition exist repeated 35 times—once for each quiz—and then you have to worry about only i quiz at a time inside the loop. Kickoff you'll create the actual quiz file. It needs to have a unique filename and should also have some kind of standard header in information technology, with places for the student to make full in a proper noun, appointment, and class period. Then yous'll need to go a list of states in randomized order, which tin be used later to create the questions and answers for the quiz.
Add the following lines of lawmaking to randomQuizGenerator.py :
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random order, along with the answer key. -- snip -- # Generate 35 quiz files. for quizNum in range(35): # Create the quiz and answer cardinal files. ❶ quizFile = open('capitalsquiz%s.txt' % (quizNum + 1), 'w') ❷ answerKeyFile = open up('capitalsquiz_answers%s.txt' % (quizNum + 1), 'w') # Write out the header for the quiz. ❸ quizFile.write('Proper name:\north\nDate:\northward\nPeriod:\northward\n') quizFile.write((' ' * 20) + 'State Capitals Quiz (Form %south)' % (quizNum + 1)) quizFile.write('\n\north') # Shuffle the order of the states. states = list(capitals.keys()) ❹ random.shuffle(states) # TODO: Loop through all 50 states, making a question for each.
The filenames for the quizzes volition be capitalsquiz<Northward>.txt , where <Due north> is a unique number for the quiz that comes from quizNum
, the for
loop'south counter. The answer key for capitalsquiz<N>.txt will be stored in a text file named capitalsquiz_answers<N>.txt . Each time through the loop, the %south
placeholder in 'capitalsquiz%s.txt'
and 'capitalsquiz_answers%s.txt'
volition exist replaced by (quizNum + ane)
, so the first quiz and answer fundamental created will exist capitalsquiz1.txt and capitalsquiz_answers1.txt . These files will be created with calls to the open()
function at ❶ and ❷, with 'w'
every bit the second argument to open them in write mode.
The write()
statements at ❸ create a quiz header for the pupil to fill out. Finally, a randomized listing of Us states is created with the help of the random.shuffle()
role ❹, which randomly reorders the values in whatsoever list that is passed to it.
Step 3: Create the Answer Options
Now yous demand to generate the respond options for each question, which volition be multiple pick from A to D. You lot'll need to create another for
loop—this one to generate the content for each of the 50 questions on the quiz. And then in that location will exist a third for
loop nested within to generate the multiple-selection options for each question. Make your lawmaking look like the following:
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random society, along with the answer key. -- snip -- # Loop through all l states, making a question for each. for questionNum in range(fifty): # Get correct and wrong answers. ❶ correctAnswer = capitals[states[questionNum]] ❷ wrongAnswers = list(capitals.values()) ❸ del wrongAnswers[wrongAnswers.index(correctAnswer)] ❹ wrongAnswers = random.sample(wrongAnswers, three) ❺ answerOptions = wrongAnswers + [correctAnswer] ❻ random.shuffle(answerOptions) # TODO: Write the question and answer options to the quiz file. # TODO: Write the answer central to a file.
The right answer is easy to become—it's stored as a value in the capitals
lexicon ❶. This loop will loop through us in the shuffled states
list, from states[0]
to states[49]
, detect each country in capitals
, and shop that land's corresponding uppercase in correctAnswer
.
The list of possible wrong answers is trickier. You lot can get it past duplicating all the values in the capitals
lexicon ❷, deleting the correct answer ❸, and selecting 3 random values from this list ❹. The random.sample()
part makes information technology like shooting fish in a barrel to do this selection. Its showtime argument is the listing you want to select from; the second statement is the number of values you desire to select. The full list of answer options is the combination of these 3 wrong answers with the correct answers ❺. Finally, the answers need to be randomized ❻ and so that the correct response isn't ever choice D.
Stride 4: Write Content to the Quiz and Answer Key Files
All that is left is to write the question to the quiz file and the answer to the answer key file. Make your code await similar the following:
#! python3 # randomQuizGenerator.py - Creates quizzes with questions and answers in # random club, along with the reply cardinal. -- snip -- # Loop through all l states, making a question for each. for questionNum in range(50): -- snip -- # Write the question and the answer options to the quiz file. quizFile.write('%s. What is the capital of %s?\n' % (questionNum + 1, states[questionNum])) ❶ for i in range(4): ❷ quizFile.write(' %s. %s\due north' % ('ABCD'[i], answerOptions[i])) quizFile.write('\northward') # Write the respond key to a file. ❸ answerKeyFile.write('%s. %s\due north' % (questionNum + 1, 'ABCD'[ answerOptions.alphabetize(correctAnswer)])) quizFile.close() answerKeyFile.close()
A for
loop that goes through integers 0
to 3
will write the answer options in the answerOptions
list ❶. The expression 'ABCD'[i]
at ❷ treats the string 'ABCD'
every bit an array and will evaluate to 'A'
,'B'
, 'C'
, so 'D'
on each respective iteration through the loop.
In the terminal line ❸, the expression answerOptions.index(correctAnswer)
will find the integer alphabetize of the right reply in the randomly ordered answer options, and 'ABCD'[answerOptions.index(correctAnswer)]
will evaluate to the right answer's letter of the alphabet to be written to the answer key file.
After you run the program, this is how your capitalsquiz1.txt file will look, though of course your questions and answer options may be dissimilar from those shown here, depending on the outcome of your random.shuffle()
calls:
Name: Date: Period: State Capitals Quiz (Grade i) 1. What is the capital of West Virginia? A. Hartford B. Santa Fe C. Harrisburg D. Charleston 2. What is the capital of Colorado? A. Raleigh B. Harrisburg C. Denver D. Lincoln -- snip --
The corresponding capitalsquiz_answers1.txt text file volition look like this:
1. D 2. C 3. A four. C -- snip --
Project: Multiclipboard
Say y'all accept the boring task of filling out many forms in a web folio or software with several text fields. The clipboard saves you from typing the aforementioned text over and over again. But only one affair tin can exist on the clipboard at a time. If you take several different pieces of text that yous need to copy and paste, y'all accept to go along highlighting and copying the same few things over and over again.
You tin can write a Python program to keep track of multiple pieces of text. This "multiclipboard" will be named mcb.pyw (since "mcb" is shorter to blazon than "multiclipboard"). The .pyw extension ways that Python won't bear witness a Final window when it runs this programme. (See Appendix B for more details.)
The program volition relieve each piece of clipboard text under a keyword. For example, when you run py mcb.pyw save spam
, the current contents of the clipboard volition be saved with the keyword spam . This text can after be loaded to the clipboard again by running py mcb.pyw spam
. And if the user forgets what keywords they have, they can run py mcb.pyw list
to copy a list of all keywords to the clipboard.
Here'southward what the programme does:
-
The command line argument for the keyword is checked.
-
If the argument is
save
, and so the clipboard contents are saved to the keyword. -
If the argument is
list
, then all the keywords are copied to the clipboard. -
Otherwise, the text for the keyword is copied to the clipboard.
This means the code will need to do the following:
-
Read the command line arguments from
sys.argv
. -
Read and write to the clipboard.
-
Save and load to a shelf file.
If you utilize Windows, you lot can hands run this script from the Run... window by creating a batch file named mcb.bat with the following content:
@pyw.exe C:\Python34\mcb.pyw %*
Step 1: Comments and Shelf Setup
Allow's start by making a skeleton script with some comments and basic setup. Make your lawmaking expect like the following:
#! python3 # mcb.pyw - Saves and loads pieces of text to the clipboard. ❶ # Usage: py.exe mcb.pyw salvage <keyword> - Saves clipboard to keyword. # py.exe mcb.pyw <keyword> - Loads keyword to clipboard. # py.exe mcb.pyw list - Loads all keywords to clipboard. ❷ import shelve, pyperclip, sys ❸ mcbShelf = shelve.open('mcb') # TODO: Save clipboard content. # TODO: List keywords and load content. mcbShelf.close()
Information technology'due south mutual practice to put general usage information in comments at the top of the file ❶. If y'all ever forget how to run your script, you can e'er await at these comments for a reminder. Then you import your modules ❷. Copying and pasting will require the pyperclip
module, and reading the control line arguments will require the sys
module. The shelve
module will also come in handy: Whenever the user wants to save a new piece of clipboard text, yous'll save it to a shelf file. Then, when the user wants to paste the text back to their clipboard, y'all'll open the shelf file and load it back into your programme. The shelf file will exist named with the prefix mcb ❸.
Footstep 2: Save Clipboard Content with a Keyword
The plan does different things depending on whether the user wants to salvage text to a keyword, load text into the clipboard, or listing all the existing keywords. Permit'south deal with that kickoff example. Make your code expect like the following:
#! python3 # mcb.pyw - Saves and loads pieces of text to the clipboard. -- snip -- # Relieve clipboard content. ❶ if len(sys.argv) == 3 and sys.argv[1].lower() == 'salve': ❷ mcbShelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == ii: ❸ # TODO: Listing keywords and load content. mcbShelf.shut()
If the first command line argument (which will always be at index 1
of the sys.argv
listing) is 'save'
❶, the 2d command line statement is the keyword for the current content of the clipboard. The keyword will exist used as the key for mcbShelf
, and the value will be the text currently on the clipboard ❷.
If there is only one control line argument, you lot will assume it is either 'list'
or a keyword to load content onto the clipboard. Y'all will implement that lawmaking later. For now, but put a TODO
comment there ❸.
Step 3: List Keywords and Load a Keyword'southward Content
Finally, let'due south implement the ii remaining cases: The user wants to load clipboard text in from a keyword, or they desire a list of all available keywords. Make your lawmaking expect like the post-obit:
#! python3 # mcb.pyw - Saves and loads pieces of text to the clipboard. -- snip -- # Save clipboard content. if len(sys.argv) == iii and sys.argv[i].lower() == 'save': mcbShelf[sys.argv[2]] = pyperclip.paste() elif len(sys.argv) == 2: # List keywords and load content. ❶ if sys.argv[ane].lower() == 'listing': ❷ pyperclip.copy(str(listing(mcbShelf.keys()))) elif sys.argv[i] in mcbShelf: ❸ pyperclip.copy(mcbShelf[sys.argv[1]]) mcbShelf.close()
If there is only one command line argument, first let's check whether it's 'list'
❶. If so, a string representation of the listing of shelf keys will be copied to the clipboard ❷. The user can paste this listing into an open text editor to read it.
Otherwise, yous tin can assume the command line argument is a keyword. If this keyword exists in the mcbShelf
shelf as a key, you lot can load the value onto the clipboard ❸.
And that's it! Launching this program has different steps depending on what operating system your figurer uses. See Appendix B for details for your operating system.
Remember the password locker program you created in Chapter 6 that stored the passwords in a dictionary. Updating the passwords required changing the source code of the program. This isn't ideal because boilerplate users don't experience comfy changing source lawmaking to update their software. As well, every time yous alter the source code to a programme, you run the run a risk of accidentally introducing new bugs. Past storing the information for a program in a different identify than the code, you can make your programs easier for others to use and more resistant to bugs.
Summary
Files are organized into folders (also called directories), and a path describes the location of a file. Every program running on your calculator has a electric current working directory, which allows you lot to specify file paths relative to the current location instead of always typing the full (or absolute) path. The os.path
module has many functions for manipulating file paths.
Your programs can too directly interact with the contents of text files. The open()
function can open these files to read in their contents as one large cord (with the read()
method) or equally a list of strings (with the readlines()
method). The open up()
function tin can open files in write or append mode to create new text files or add together to existing text files, respectively.
In previous chapters, you used the clipboard as a mode of getting large amounts of text into a program, rather than typing information technology all in. At present you can have your programs read files directly from the difficult bulldoze, which is a large improvement, since files are much less volatile than the clipboard.
In the next chapter, you volition learn how to handle the files themselves, past copying them, deleting them, renaming them, moving them, and more than.
Practise Questions
Q: | 1. What is a relative path relative to? |
Q: | 2. What does an absolute path get-go with? |
Q: | 3. What do the |
Q: | 4. What are the |
Q: | 5. In C:\salary\eggs\spam.txt , which part is the dir name, and which part is the base name? |
Q: | vi. What are the iii "mode" arguments that tin can be passed to the |
Q: | 7. What happens if an existing file is opened in write mode? |
Q: | 8. What is the difference between the |
Q: | 9. What data structure does a shelf value resemble? |
Practice Projects
For practice, design and write the post-obit programs.
Extending the Multiclipboard
Extend the multiclipboard program in this chapter so that it has a delete <keyword>
control line statement that will delete a keyword from the shelf. Then add a delete
control line argument that volition delete all keywords.
Mad Libs
Create a Mad Libs program that reads in text files and lets the user add their own text anywhere the give-and-take ADJECTIVE , Noun , ADVERB , or VERB appears in the text file. For case, a text file may look similar this:
The Describing word panda walked to the Noun and and so VERB. A nearby NOUN was unaffected by these events.
The plan would find these occurrences and prompt the user to replace them.
Enter an describing word: silly Enter a substantive: chandelier Enter a verb: screamed Enter a noun: pickup truck
The following text file would then be created:
The dizzy panda walked to the chandelier and then screamed. A nearby pickup truck was unaffected by these events.
The results should be printed to the screen and saved to a new text file.
Regex Search
Write a plan that opens all . txt files in a folder and searches for any line that matches a user-supplied regular expression. The results should be printed to the screen.
Source: https://automatetheboringstuff.com/chapter8/
0 Response to "what is the standard file path in python to be opened"
Post a Comment