id
int64
0
25.6k
text
stringlengths
0
4.59k
2,700
to open file with the open(functionyou pass it string path indicating the file you want to openit can be either an absolute or relative path the open(function returns file object try it by creating text file named hello txt using notepad or textedit type helloworldas the content of this text file and save it in your user home folder then enter the following into the interactive shellhellofile open(path home('hello txt'the open(function can also accept strings if you're using windowsenter the following into the interactive shellhellofile open(' :\\users\\your_home_folder\\hello txt'if you're using macosenter the following into the interactive shell insteadhellofile open('/users/your_home_folder/hello txt'make sure to replace your_home_folder with your computer username for examplemy username is also ' enter ' :\\users\\al\\hello txton windows note that the open(function only accepts path objects as of python in previous versionsyou always need to pass string to open(both these commands will open the file in "reading plaintextmodeor read mode for short when file is opened in read modepython lets you only read data from the fileyou can' write or modify it in any way read mode is the default mode for files you open in python but if you don' want to rely on python' defaultsyou can explicitly specify the mode by passing the string value 'ras second argument to open(so open('/users/al/hello txt'' 'and open('/users/al/hello txt'do the same thing the call to open(returns file object file object represents file on your computerit is simply another type of value in pythonmuch like the lists and dictionaries you're already familiar with in the previous exampleyou stored the file object in the variable hellofile nowwhenever you want to read from or write to the fileyou can do so by calling methods on the file object in hellofile reading the contents of files now that you have file objectyou can start reading from it if you want to read the entire contents of file as string valueuse the file object' read(method let' continue with the hello txt file object you stored in hellofile enter the following into the interactive shellhellocontent hellofile read(hellocontent 'helloworld!reading and writing files
2,701
read(method returns the string that is stored in the file alternativelyyou can use the readlines(method to get list of string values from the fileone string for each line of text for examplecreate file named sonnet txt in the same directory as hello txt and write the following text in itwhenin disgrace with fortune and men' eyesi all alone beweep my outcast stateand trouble deaf heaven with my bootless criesand look upon myself and curse my fatemake sure to separate the four lines with line breaks then enter the following into the interactive shellsonnetfile open(path home('sonnet txt'sonnetfile readlines([whenin disgrace with fortune and men' eyes,\ ' all alone beweep my outcast state,\ 'and trouble deaf heaven with my bootless cries,\ 'and look upon myself and curse my fate,'note thatexcept for the last line of the fileeach of the string values ends with newline character \ list of strings is often easier to work with than single large string value writing to files python allows you to write content to file in way similar to how the print(function "writesstrings to the screen you can' write to file you've opened in read modethough insteadyou need to open it in "write plaintextmode or "append plaintextmodeor write mode and append mode for short write mode will overwrite the existing file and start from scratchjust like when you overwrite variable' value with new value pass 'was the second argument to open(to open the file in write mode append modeon the other handwill append text to the end of the existing file you can think of this as appending to list in variablerather than overwriting the variable altogether pass 'aas the second argument to open(to open the file in append mode if the filename passed to open(does not existboth write and append mode will create newblank file after reading or writing filecall the close(method before opening the file again let' put these concepts together enter the following into the interactive shellbaconfile open('bacon txt'' 'baconfile write('helloworld!\ ' baconfile close(baconfile open('bacon txt'' 'baconfile write('bacon is not vegetable '
2,702
baconfile close(baconfile open('bacon txt'content baconfile read(baconfile close(print(contenthelloworldbacon is not vegetable firstwe open bacon txt in write mode since there isn' bacon txt yetpython creates one calling write(on the opened file and passing write(the string argument 'helloworld/nwrites the string to the file and returns the number of characters writtenincluding the newline then we close the file to add text to the existing contents of the file instead of replacing the string we just wrotewe open the file in append mode we write 'bacon is not vegetable to the file and close it finallyto print the file contents to the screenwe open the file in its default read modecall read()store the resulting file object in contentclose the fileand print content note that the write(method does not automatically add newline character to the end of the string like the print(function does you will have to add this character yourself as of python you can also pass path object to the open(function instead of string for the filename saving variables with the shelve module you can save variables in your python programs to binary shelf files using the shelve module this wayyour program can restore data to variables from the hard drive the shelve module will let you add save and open features to your program for exampleif you ran program and entered some configuration settingsyou could save those settings to shelf file and then have the program load them the next time it is run enter the following into the interactive shellimport shelve shelffile shelve open('mydata'cats ['zophie''pooka''simon'shelffile['cats'cats shelffile close(to read and write data using the shelve moduleyou first import shelve call shelve open(and pass it filenameand then store the returned shelf value in variable you can make changes to the shelf value as if it were dictionary when you're donecall close(on the shelf value hereour shelf value is stored in shelffile we create list cats and write shelffile['cats'cats to store the list in shelffile as value associated with the key 'cats(like in dictionarythen we call close(on shelffile note that as of python reading and writing files
2,703
it path object after running the previous code on windowsyou will see three new files in the current working directorymydata bakmydata datand mydata dir on macosonly single mydata db file will be created these binary files contain the data you stored in your shelf the format of these binary files is not importantyou only need to know what the shelve module doesnot how it does it the module frees you from worrying about how to store your program' data to file your programs can use the shelve module to later reopen and retrieve the data from these shelf files shelf values don' have to be opened in read or write mode--they can do both once opened enter the following into the interactive shellshelffile shelve open('mydata'type(shelffileshelffile['cats'['zophie''pooka''simon'shelffile close(herewe open the shelf files to check that our data was stored correctly entering shelffile['cats'returns the same list that we stored earlierso we know that the list is correctly storedand we call close(just like dictionariesshelf 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 listsyou should pass them to the list(function to get them in list form enter the following into the interactive shellshelffile shelve open('mydata'list(shelffile keys()['cats'list(shelffile values()[['zophie''pooka''simon']shelffile close(plaintext is useful for creating files that you'll read in text editor such as notepad or texteditbut if you want to save data from your python programsuse the shelve module saving variables with the pprint pformat(function recall from "pretty printingon page that the pprint pprint(function will "pretty printthe contents of list or dictionary to the screenwhile the pprint pformat(function will return this same text as string instead of printing it not only is this string formatted to be easy to readbut it is also syntactically correct python code say you have dictionary stored in variable and you want to save this variable and its contents for future use using
2,704
will be your very own module that you can import whenever you want to use the variable stored in it for exampleenter the following into the interactive shellimport pprint cats [{'name''zophie''desc''chubby'}{'name''pooka''desc''fluffy'}pprint pformat(cats"[{'desc''chubby''name''zophie'}{'desc''fluffy''name''pooka'}]fileobj open('mycats py'' 'fileobj write('cats pprint pformat(cats'\ ' fileobj close(herewe import pprint to let us use pprint pformat(we have list of dictionariesstored in variable cats to keep the list in cats available even after we close the shellwe use pprint pformat(to return it as string once we have the data in cats as stringit' easy to write the string to filewhich we'll call mycats py the modules that an import statement imports are themselves just python scripts when the string from pprint pformat(is saved to py filethe file is module that can be imported just like any other and since python scripts are themselves just text files with the py file extensionyour python programs can even generate other python programs you can then import these files into scripts import mycats mycats cats [{'name''zophie''desc''chubby'}{'name''pooka''desc''fluffy'}mycats cats[ {'name''zophie''desc''chubby'mycats cats[ ]['name''zophiethe benefit of creating py file (as opposed to saving variables with the shelve moduleis that because it is text filethe contents of the file can be read and modified by anyone with simple text editor for most applicationshoweversaving data using the shelve module is the preferred way to save variables to file only basic data types such as integersfloatsstringslistsand dictionaries can be written to file as simple text file objectsfor examplecannot be encoded as text projectgenerating random quiz files say you're geography teacher with students in your class and you want to give pop quiz on us state capitals alasyour class has few bad eggs in itand you can' trust the students not to cheat you' like to randomize the reading and writing files
2,705
be lengthy and boring affair fortunatelyyou know some python here is what the program does creates different quizzes creates multiple-choice questions for each quizin random order provides the correct answer and three random wrong answers for each questionin random order writes the quizzes to text files writes the answer keys to text files this means the code will need to do the following store the states and their capitals in dictionary call open()write()and close(for the quiz and answer key text files use random shuffle(to randomize the order of the questions and multiple-choice options step store the quiz data in dictionary the first step is to create skeleton script and fill it with your quiz data create file named randomquizgenerator pyand make it look like the following#python randomquizgenerator py creates quizzes with questions and answers in random orderalong with the answer key import random the quiz data keys are states and values are their capitals capitals {'alabama''montgomery''alaska''juneau''arizona''phoenix''arkansas''little 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 jersey''trenton''new mexico''santa fe''new york''albany''north carolina''raleigh''north dakota''bismarck''ohio''columbus''oklahoma''oklahoma city''oregon''salem''pennsylvania''harrisburg''rhode island''providence''south carolina''columbia''south dakota''pierre''tennessee''nashville''texas''austin''utah''salt lake city''vermont''montpelier''virginia''richmond''washington''olympia''west virginia''charleston''wisconsin''madison''wyoming''cheyenne'generate quiz files
2,706
todocreate the quiz and answer key files todowrite out the header for the quiz todoshuffle the order of the states todoloop through all statesmaking question for each since this program will be randomly ordering the questions and answersyou'll need to import the random module to make use of its functions the capitals variable contains dictionary with us states as keys and their capitals as values and since you want to create quizzesthe code that actually generates the quiz and answer key files (marked with todo comments for nowwill go inside for loop that loops times (this number can be changed to generate any number of quiz files step create the quiz file and shuffle the question order now it' time to start filling in those todos the code in the loop will be repeated times--once for each quiz-so you have to worry about only one quiz at time within the loop first you'll create the actual quiz file it needs to have unique filename and should also have some kind of standard header in itwith places for the student to fill in namedateand class period then you'll need to get list of states in randomized orderwhich can be used later to create the questions and answers for the quiz add the following lines of code to randomquizgenerator py#python randomquizgenerator py creates quizzes with questions and answers in random orderalong with the answer key --snip-generate quiz files for quiznum in range( )create the quiz and answer key files quizfile open( 'capitalsquiz{quiznum txt'' 'answerkeyfile open( 'capitalsquiz_answers{quiznum txt'' 'write out the header for the quiz quizfile write('name:\ \ndate:\ \nperiod:\ \ 'quizfile write(( 'state capitals quiz (form{quiznum })'quizfile write('\ \ 'shuffle the order of the states states list(capitals keys()random shuffle(statestodoloop through all statesmaking question for each reading and writing files
2,707
unique number for the quiz that comes from quiznumthe for loop' counter the answer key for capitalsquiz txt will be stored in text file named capitalsquiz_answers txt each time through the loopthe {quiznum placeholder in 'capitalsquiz{quiznum txtand 'capitalsquiz_answers {quiznum txtwill be replaced by the unique numberso the first quiz and answer key created will be capitalsquiz txt and capitalsquiz_answers txt these files will be created with calls to the open(function at and with 'was the second argument to open them in write mode the write(statements at create quiz header for the student to fill out finallya randomized list of us states is created with the help of the random shuffle(function which randomly reorders the values in any list that is passed to it step create the answer options now you need to generate the answer options for each questionwhich will be multiple choice from to you'll need to create another for loop--this one to generate the content for each of the questions on the quiz then there will be third for loop nested inside to generate the multiple-choice options for each question make your code look like the following#python randomquizgenerator py creates quizzes with questions and answers in random orderalong with the answer key --snip-loop through all statesmaking question for each for questionnum in range( )get right and wrong answers correctanswer capitals[states[questionnum]wronganswers list(capitals values()del wronganswers[wronganswers index(correctanswer)wronganswers random sample(wronganswers answeroptions wronganswers [correctanswerrandom shuffle(answeroptionstodowrite the question and answer options to the quiz file todowrite the answer key to file the correct answer is easy to get--it' stored as value in the capitals dictionary this loop will loop through the states in the shuffled states listfrom states[ to states[ ]find each state in capitalsand store that state' corresponding capital in correctanswer the list of possible wrong answers is trickier you can get it by duplicating all the values in the capitals dictionary deleting the correct answer and selecting three random values from this list the random sample(function makes it easy to do this selection its first argument is the list you want
2,708
select the full list of answer options is the combination of these three wrong answers with the correct answers finallythe answers need to be randomized so that the correct response isn' always choice step 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 look like the following#python randomquizgenerator py creates quizzes with questions and answers in random orderalong with the answer key --snip-loop through all statesmaking question for each for questionnum in range( )--snip-write the question and the answer options to the quiz file quizfile write( '{questionnum what is the capital of {states[questionnum]}?\ 'for in range( )quizfile write( {'abcd'[ ]answeroptions[ ]}\ "quizfile write('\ 'write the answer key to file answerkeyfile write( "{questionnum {'abcd'[answeroptions index(correctanswer)]}"quizfile close(answerkeyfile close( for loop that goes through integers to will write the answer options in the answeroptions list the expression 'abcd'[iat treats the string 'abcdas an array and will evaluate to ' ',' '' 'and then 'don each respective iteration through the loop in the final line the expression answeroptions index(correctanswerwill find the integer index of the correct answer in the randomly ordered answer optionsand 'abcd'[answeroptions index(correctanswer)will evaluate to the correct answer' letter to be written to the answer key file after you run the programthis is how your capitalsquiz txt file will lookthough of course your questions and answer options may be different from those shown heredepending on the outcome of your random shuffle(callsnamedateperiodstate capitals quiz (form reading and writing files
2,709
hartford santa fe harrisburg charleston what is the capital of coloradoa raleigh harrisburg denver lincoln --snip-the corresponding capitalsquiz_answers txt text file will look like this --snip-projectupdatable multi-clipboard let' rewrite the "multi-clipboardprogram from so that it uses the shelve module the user will now be able to save new strings to load to the clipboard without having to modify the source code we'll name this new program mcb pyw (since "mcbis shorter to type than "multi-clipboard"the pyw extension means that python won' show terminal window when it runs this program (see appendix for more details the program will save each piece of clipboard text under keyword for examplewhen you run py mcb pyw save spamthe current contents of the clipboard will be saved with the keyword spam this text can later be loaded to the clipboard again by running py mcb pyw spam and if the user forgets what keywords they havethey can run py mcb pyw list to copy list of all keywords to the clipboard here' what the program does the command line argument for the keyword is checked if the argument is savethen the clipboard contents are saved to the keyword if the argument is listthen all the keywords are copied to the clipboard otherwisethe 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 shelf file
2,710
window by creating batch file named mcb bat with the following content@pyw exe :\python \mcb pyw %step comments and shelf setup let' start by making skeleton script with some comments and basic setup make your code look like the following#python mcb pyw saves and loads pieces of text to the clipboard usagepy exe mcb pyw save saves clipboard to keyword py exe mcb pyw loads keyword to clipboard py exe mcb pyw list loads all keywords to clipboard import shelvepyperclipsys mcbshelf shelve open('mcb'todosave clipboard content todolist keywords and load content mcbshelf close(it' common practice to put general usage information in comments at the top of the file if you ever forget how to run your scriptyou can always look at these comments for reminder then you import your modules copying and pasting will require the pyperclip moduleand reading the command line arguments will require the sys module the shelve module will also come in handywhenever the user wants to save new piece of clipboard textyou'll save it to shelf file thenwhen the user wants to paste the text back to their clipboardyou'll open the shelf file and load it back into your program the shelf file will be named with the prefix mcb step save clipboard content with keyword the program does different things depending on whether the user wants to save text to keywordload text into the clipboardor list all the existing keywords let' deal with that first case make your code look like the following#python mcb pyw saves and loads pieces of text to the clipboard --snip-save clipboard content if len(sys argv= and sys argv[ lower(='save'mcbshelf[sys argv[ ]pyperclip paste(elif len(sys argv= reading and writing files
2,711
mcbshelf close(if the first command line argument (which will always be at index of the sys argv listis 'savethe second command line argument is the keyword for the current content of the clipboard the keyword will be used as the key for mcbshelfand the value will be the text currently on the clipboard if there is only one command line argumentyou will assume it is either 'listor keyword to load content onto the clipboard you will implement that code later for nowjust put todo comment there step list keywords and load keyword' content finallylet' implement the two remaining casesthe user wants to load clipboard text in from keywordor they want list of all available keywords make your code look like the following#python mcb pyw saves and loads pieces of text to the clipboard --snip-save clipboard content if len(sys argv= and sys argv[ lower(='save'mcbshelf[sys argv[ ]pyperclip paste(elif len(sys argv= list keywords and load content if sys argv[ lower(='list'pyperclip copy(str(list(mcbshelf keys()))elif sys argv[ in mcbshelfpyperclip copy(mcbshelf[sys argv[ ]]mcbshelf close(if there is only one command line argumentfirst let' check whether it' 'listif soa string representation of the list of shelf keys will be copied to the clipboard the user can paste this list into an open text editor to read it otherwiseyou can assume the command line argument is keyword if this keyword exists in the mcbshelf shelf as keyyou can load the value onto the clipboard and that' itlaunching this program has different steps depending on what operating system your computer uses see appendix for details recall the password locker program you created in that stored the passwords in dictionary updating the passwords required changing the source code of the program this isn' idealbecause average users don' feel comfortable changing source code to update their software alsoevery time you modify the source code to programyou run the risk of accidentally introducing new bugs by storing the data for program in different place than the codeyou can make your programs easier for others to use and more resistant to bugs
2,712
files are organized into folders (also called directories)and path describes the location of file every program running on your computer has current working directorywhich allows you to specify file paths relative to the current location instead of always typing the full (or absolutepath the pathlib and os path modules have many functions for manipulating file paths your programs can also directly interact with the contents of text files the open(function can open these files to read in their contents as one large string (with the read(methodor as list of strings (with the readlines(methodthe open(function can open files in write or append mode to create new text files or add to existing text filesrespectively in previous you used the clipboard as way of getting large amounts of text into programrather than typing it all in now you can have your programs read files directly from the hard drivewhich is big improvementsince files are much less volatile than the clipboard in the next you will learn how to handle the files themselvesby copying themdeleting themrenaming themmoving themand more practice questions what is relative path relative towhat does an absolute path start withwhat does path(' :/users''alevaluate to on windowswhat does ' :/users'alevaluate to on windowswhat do the os getcwd(and os chdir(functions dowhat are the and foldersin :\bacon\eggs\spam txtwhich part is the dir nameand which part is the base name what are the three "modearguments that can be passed to the open(function what happens if an existing file is opened in write mode what is the difference between the read(and readlines(methods what data structure does shelf value resemblepractice projects for practicedesign and write the following programs extending the multi-clipboard extend the multi-clipboard program in this so that it has delete command line argument that will delete keyword from the shelf then add delete command line argument that will delete all keywords reading and writing files
2,713
create mad libs program that reads in text files and lets the user add their own text anywhere the word adjectivenounadverbor verb appears in the text file for examplea text file may look like thisthe adjective panda walked to the noun and then verb nearby noun was unaffected by these events the program would find these occurrences and prompt the user to replace them enter an adjectivesilly enter nounchandelier enter verbscreamed enter nounpickup truck the following text file would then be createdthe silly panda walked to the chandelier and then screamed nearby pickup truck was unaffected by these events the results should be printed to the screen and saved to new text file regex search write program that opens all txt files in folder and searches for any line that matches user-supplied regular expression the results should be printed to the screen
2,714
org anizing files in the previous you learned how to create and write to new files in python your programs can also organize preexisting files on the hard drive maybe you've had the experience of going through folder full of dozenshundredsor even thousands of files and copyingrenamingmovingor compressing them all by hand or consider tasks such as thesemaking copies of all pdf files (and only the pdf filesin every subfolder of folder removing the leading zeros in the filenames for every file in folder of hundreds of files named spam txtspam txtspam txtand so on compressing the contents of several folders into one zip file (which could be simple backup system
2,715
programming your computer to do these tasksyou can transform it into quick-working file clerk who never makes mistakes as you begin working with filesyou may find it helpful to be able to quickly see what the extension txtpdfjpgand so onof file is with macos and linuxyour file browser most likely shows extensions automatically with windowsfile extensions may be hidden by default to show extensionsgo to start control panelappearance and personalizationfolder options on the view tabunder advanced settingsuncheck the hide extensions for known file types checkbox the shutil module the shutil (or shell utilitiesmodule has functions to let you copymoverenameand delete files in your python programs to use the shutil functionsyou will first need to use import shutil copying files and folders the shutil module provides functions for copying filesas well as entire folders calling shutil copy(sourcedestinationwill copy the file at the path source to the folder at the path destination (both source and destination can be strings or path objects if destination is filenameit will be used as the new name of the copied file this function returns string or path object of the copied file enter the following into the interactive shell to see how shutil copy(worksimport shutilos from pathlib import path path home(shutil copy( 'spam txt' 'some_folder'' :\\users\\al\\some_folder\\spam txtshutil copy( 'eggs txt' 'some_folder/eggs txt'windowspath(' :/users/al/some_folder/eggs txt'the first shutil copy(call copies the file at :\users\al\spam txt to the folder :\users\al\some_folder the return value is the path of the newly copied file note that since folder was specified as the destination the original spam txt filename is used for the newcopied file' filename the second shutil copy(call also copies the file at :\users\al\eggs txt to the folder :\users\al\some_folder but gives the copied file the name eggs txt while shutil copy(will copy single fileshutil copytree(will copy an entire folder and every folder and file contained in it calling shutil copytree(sourcedestinationwill copy the folder at the path sourcealong with all of its files and subfoldersto the folder at the path destination the source and destination parameters are both strings the function returns string of the path of the copied folder
2,716
import shutilos from pathlib import path path home(shutil copytree( 'spam' 'spam_backup'windowspath(' :/users/al/spam_backup'the shutil copytree(call creates new folder named spam_backup with the same content as the original spam folder you have now safely backed up your preciousprecious spam moving and renaming files and folders calling shutil move(sourcedestinationwill move the file or folder at the path source to the path destination and will return string of the absolute path of the new location if destination points to folderthe source file gets moved into destination and keeps its current filename for exampleenter the following into the interactive shellimport shutil shutil move(' :\\bacon txt'' :\\eggs'' :\\eggs\\bacon txtassuming folder named eggs already exists in the :directorythis shutil move(call says"move :\bacon txt into the folder :\eggs if there had been bacon txt file already in :\eggsit would have been overwritten since it' easy to accidentally overwrite files in this wayyou should take some care when using move(the destination path can also specify filename in the following examplethe source file is moved and renamed shutil move(' :\\bacon txt'' :\\eggs\\new_bacon txt'' :\\eggs\\new_bacon txtthis line says"move :\bacon txt into the folder :\eggsand while you're at itrename that bacon txt file to new_bacon txt both of the previous examples worked under the assumption that there was folder eggs in the :directory but if there is no eggs folderthen move(will rename bacon txt to file named eggs shutil move(' :\\bacon txt'' :\\eggs'' :\\eggsheremove(can' find folder named eggs in the :directory and so assumes that destination must be specifying filenamenot folder so the bacon txt text file is renamed to eggs ( text file without the txt file extension)--probably not what you wantedthis can be tough-to-spot bug in your programs since the move(call can happily do something that might be organizing files
2,717
be careful when using move(finallythe folders that make up the destination must already existor else python will throw an exception enter the following into the interactive shellshutil move('spam txt'' :\\does_not_exist\\eggs\\ham'traceback (most recent call last)--snip-filenotfounderror[errno no such file or directory' :\\does_not_exist\eggs\\hampython looks for eggs and ham inside the directory does_not_exist it doesn' find the nonexistent directoryso it can' move spam txt to the path you specified permanently deleting files and folders you can delete single file or single empty folder with functions in the os modulewhereas to delete folder and all of its contentsyou use the shutil module calling os unlink(pathwill delete the file at path calling os rmdir(pathwill delete the folder at path this folder must be empty of any files or folders calling shutil rmtree(pathwill remove the folder at pathand all files and folders it contains will also be deleted be careful when using these functions in your programsit' often good idea to first run your program with these calls commented out and with print(calls added to show the files that would be deleted here is python program that was intended to delete files that have the txt file extension but has typo (highlighted in boldthat causes it to delete rxt files insteadimport os from pathlib import path for filename in path home(glob('rxt')os unlink(filenameif you had any important files ending with rxtthey would have been accidentallypermanently deleted insteadyou should have first run the program like thisimport os from pathlib import path for filename in path home(glob('rxt')#os unlink(filenameprint(filename
2,718
will print the filename of the file that would have been deleted running this version of the program first will show you that you've accidentally told the program to delete rxt files instead of txt files once you are certain the program works as intendeddelete the print(filenameline and uncomment the os unlink(filenameline then run the program again to actually delete the files safe deletes with the send trash module since python' built-in shutil rmtree(function irreversibly deletes files and foldersit can be dangerous to use much better way to delete files and folders is with the third-party send trash module you can install this module by running pip install --user send trash from terminal window (see appendix for more in-depth explanation of how to install third-party modules using send trash is much safer than python' regular delete functionsbecause it will send folders and files to your computer' trash or recycle bin instead of permanently deleting them if bug in your program deletes something with send trash you didn' intend to deleteyou can later restore it from the recycle bin after you have installed send trashenter the following into the interactive shellimport send trash baconfile open('bacon txt'' 'creates the file baconfile write('bacon is not vegetable ' baconfile close(send trash send trash('bacon txt'in generalyou should always use the send trash send trash(function to delete files and folders but while sending files to the recycle bin lets you recover them laterit will not free up disk space like permanently deleting them does if you want your program to free up disk spaceuse the os and shutil functions for deleting files and folders note that the send trash(function can only send files to the recycle binit cannot pull files out of it walking directory tree say you want to rename every file in some folder and also every file in every subfolder of that folder that isyou want to walk through the directory treetouching each file as you go writing program to do this could get trickyfortunatelypython provides function to handle this process for you let' look at the :\delicious folder with its contentsshown in figure - organizing files
2,719
delicious cats catnames txt zophie jpg walnut waffles butter txt spam txt figure - an example folder that contains three folders and four files here is an example program that uses the os walk(function on the directory tree from figure - import os for foldernamesubfoldersfilenames in os walk(' :\\delicious')print('the current folder is foldernamefor subfolder in subfoldersprint('subfolder of foldername 'subfolderfor filename in filenamesprint('file inside foldername ''filenameprint(''the os walk(function is passed single string valuethe path of folder you can use os walk(in for loop statement to walk directory treemuch like how you can use the range(function to walk over range of numbers unlike range()the os walk(function will return three values on each iteration through the loopa string of the current folder' name list of strings of the folders in the current folder list of strings of the files in the current folder (by current folderi mean the folder for the current iteration of the for loop the current working directory of the program is not changed by os walk(
2,720
range( ):you can also choose the variable names for the three values listed earlier usually use the names foldernamesubfoldersand filenames when you run this programit will output the followingthe current folder is :\delicious subfolder of :\deliciouscats subfolder of :\deliciouswalnut file inside :\deliciousspam txt the current folder is :\delicious\cats file inside :\delicious\catscatnames txt file inside :\delicious\catszophie jpg the current folder is :\delicious\walnut subfolder of :\delicious\walnutwaffles the current folder is :\delicious\walnut\waffles file inside :\delicious\walnut\wafflesbutter txt since os walk(returns lists of strings for the subfolder and filename variablesyou can use these lists in their own for loops replace the print(function calls with your own custom code (or if you don' need one or both of themremove the for loops compressing files with the zipfile module you may be familiar with zip files (with the zip file extension)which can hold the compressed contents of many other files compressing file reduces its sizewhich is useful when transferring it over the internet and since zip file can also contain multiple files and subfoldersit' handy way to package several files into one this single filecalled an archive filecan then besayattached to an email your python programs can create and open (or extractzip files using functions in the zipfile module say you have zip file named example zip that has the contents shown in figure - cats catnames txt zophie jpg spam txt figure - the contents of example zip you can download this zip file from or just follow along using zip file already on your computer organizing files
2,721
to read the contents of zip filefirst you must create zipfile object (note the capital letters and fzipfile objects are conceptually similar to the file objects you saw returned by the open(function in the previous they are values through which the program interacts with the file to create zipfile objectcall the zipfile zipfile(functionpassing it string of the zip file' filename note that zipfile is the name of the python moduleand zipfile(is the name of the function for exampleenter the following into the interactive shellimport zipfileos from pathlib import path path home(examplezip zipfile zipfile( 'example zip'examplezip namelist(['spam txt''cats/''cats/catnames txt''cats/zophie jpg'spaminfo examplezip getinfo('spam txt'spaminfo file_size spaminfo compress_size 'compressed file is {round(spaminfo file_size spaminfo compress_size )} smaller!'compressed file is smaller!examplezip close( zipfile object has namelist(method that returns list of strings for all the files and folders contained in the zip file these strings can be passed to the getinfo(zipfile method to return zipinfo object about that particular file zipinfo objects have their own attributessuch as file_size and compress_size in byteswhich hold integers of the original file size and compressed file sizerespectively while zipfile object represents an entire archive filea zipinfo object holds useful information about single file in the archive the command at calculates how efficiently example zip is compressed by dividing the original file size by the compressed file size and prints this information extracting from zip files the extractall(method for zipfile objects extracts all the files and folders from zip file into the current working directory import zipfileos from pathlib import path path home(examplezip zipfile zipfile( 'example zip'examplezip extractall(examplezip close(
2,722
:optionallyyou can pass folder name to extractall(to have it extract the files into folder other than the current working directory if the folder passed to the extractall(method does not existit will be created for instanceif you replaced the call at with examplezip extractall(' :\delicious')the code would extract the files from example zip into newly created :\delicious folder the extract(method for zipfile objects will extract single file from the zip file continue the interactive shell exampleexamplezip extract('spam txt'' :\\spam txtexamplezip extract('spam txt'' :\\some\\new\\folders'' :\\some\\new\\folders\\spam txtexamplezip close(the string you pass to extract(must match one of the strings in the list returned by namelist(optionallyyou can pass second argument to extract(to extract the file into folder other than the current working directory if this second argument is folder that doesn' yet existpython will create the folder the value that extract(returns is the absolute path to which the file was extracted creating and adding to zip files to create your own compressed zip filesyou must open the zipfile object in write mode by passing 'was the second argument (this is similar to opening text file in write mode by passing 'wto the open(function when you pass path to the write(method of zipfile objectpython will compress the file at that path and add it into the zip file the write(method' first argument is string of the filename to add the second argument is the compression type parameterwhich tells the computer what algorithm it should use to compress the filesyou can always just set this value to zipfile zip_deflated (this specifies the deflate compression algorithmwhich works well on all types of data enter the following into the interactive shellimport zipfile newzip zipfile zipfile('new zip'' 'newzip write('spam txt'compress_type=zipfile zip_deflatednewzip close(this code will create new zip file named new zip that has the compressed contents of spam txt keep in mind thatjust as with writing to fileswrite mode will erase all existing contents of zip file if you want to simply add files to an existing zip filepass 'aas the second argument to zipfile zipfile(to open the zip file in append mode organizing files
2,723
to european-style dates say your boss emails you thousands of files with american-style dates (mm-dd- yin their names and needs them renamed to europeanstyle dates (dd-mm- ythis boring task could take all day to do by handlet' write program to do it instead here' what the program does it searches all the filenames in the current working directory for american-style dates when one is foundit renames the file with the month and day swapped to make it european-style this means the code will need to do the following create regex that can identify the text pattern of american-style dates call os listdir(to find all the files in the working directory loop over each filenameusing the regex to check whether it has date if it has daterename the file with shutil move(for this projectopen new file editor window and save your code as renamedates py step create regex for american-style dates the first part of the program will need to import the necessary modules and create regex that can identify mm-dd- dates the to-do comments will remind you what' left to write in this program typing them as todo makes them easy to find using mu editor' ctrl - find feature make your code look like the following#python renamedates py renames filenames with american mm-dd-yyyy date format to european dd-mm-yyyy import shutilosre create regex that matches files with the american date format datepattern re compile( """^*?all text before the date (( | )?\ )one or two digits for the month (( | | | )?\ )one or two digits for the day (( | )\ \dfour digits for the year *?)all text after the date """re verbosetodoloop over the files in the working directory todoskip files without date
2,724
todoform the european-style filename todoget the fullabsolute file paths todorename the files from this you know the shutil move(function can be used to rename filesits arguments are the name of the file to rename and the new filename because this function exists in the shutil moduleyou must import that module but before renaming the filesyou need to identify which files you want to rename filenames with dates such as spam txt and eggs zip should be renamedwhile filenames without dates such as littlebrother epub can be ignored you can use regular expression to identify this pattern after importing the re module at the topcall re compile(to create regex object passing re verbose for the second argument will allow whitespace and comments in the regex string to make it more readable the regular expression string begins with ^*?to match any text at the beginning of the filename that might come before the date the (( | )?\dgroup matches the month the first digit can be either or so the regex matches for december but also for february this digit is also optional so that the month can be or for april the group for the day is (( | | | )?\dand follows similar logic and are all valid numbers for days (yesthis regex will accept some invalid dates such as and dates have lot of thorny special cases that can be easy to miss but for simplicitythe regex in this program works well enough while is valid yearyou can just look for years in the th or st century this will keep your program from accidentally matching nondate filenames with date-like formatsuch as txt the *?)part of the regex will match any text that comes after the date step identify the date parts from the filenames nextthe program will have to loop over the list of filename strings returned from os listdir(and match them against the regex any files that do not have date in them should be skipped for filenames that have datethe matched text will be stored in several variables fill in the first three todos in your program with the following code#python renamedates py renames filenames with american mm-dd-yyyy date format to european dd-mm-yyyy --snip-loop over the files in the working directory for amerfilename in os listdir(')organizing files
2,725
skip files without date if mo =nonecontinue get the different parts of the filename beforepart mo group( monthpart mo group( daypart mo group( yearpart mo group( afterpart mo group( --snip-if the match object returned from the search(method is none then the filename in amerfilename does not match the regular expression the continue statement will skip the rest of the loop and move on to the next filename otherwisethe various strings matched in the regular expression groups are stored in variables named beforepartmonthpartdaypartyearpartand afterpart the strings in these variables will be used to form the european-style filename in the next step to keep the group numbers straighttry reading the regex from the beginningand count up each time you encounter an opening parenthesis without thinking about the codejust write an outline of the regular expression this can help you visualize the groups here' an exampledatepattern re compile( """^( all text before the date ( ( )one or two digits for the month ( ( )one or two digits for the day ( ( four digits for the year ( )all text after the date """re verboseherethe numbers through represent the groups in the regular expression you wrote making an outline of the regular expressionwith just the parentheses and group numberscan give you clearer understanding of your regex before you move on with the rest of the program step form the new filename and rename the files as the final stepconcatenate the strings in the variables made in the previous step with the european-style datethe date comes before the month fill in the three remaining todos in your program with the following code#python renamedates py renames filenames with american mm-dd-yyyy date format to european dd-mm-yyyy --snip-
2,726
eurofilename beforepart daypart '-monthpart '-yearpart afterpart get the fullabsolute file paths absworkingdir os path abspath('amerfilename os path join(absworkingdiramerfilenameeurofilename os path join(absworkingdireurofilenamerename the files print( 'renaming "{amerfilename}to "{eurofilename}'#shutil move(amerfilenameeurofilenameuncomment after testing store the concatenated string in variable named eurofilename thenpass the original filename in amerfilename and the new eurofilename variable to the shutil move(function to rename the file this program has the shutil move(call commented out and instead prints the filenames that will be renamed running the program like this first can let you double-check that the files are renamed correctly then you can uncomment the shutil move(call and run the program again to actually rename the files ideas for similar programs there are many other reasons you might want to rename large number of files to add prefix to the start of the filenamesuch as adding spam_ to rename eggs txt to spam_eggs txt to change filenames with european-style dates to american-style dates to remove the zeros from files such as spam txt projectbacking up folder into zip file say you're working on project whose files you keep in folder named :\alspythonbook you're worried about losing your workso you' like to create zip file "snapshotsof the entire folder you' like to keep different versionsso you want the zip file' filename to increment each time it is madefor examplealspythonbook_ zipalspythonbook_ zipalspythonbook_ zipand so on you could do this by handbut it is rather annoyingand you might accidentally misnumber the zip filesnames it would be much simpler to run program that does this boring task for you for this projectopen new file editor window and save it as backuptozip py step figure out the zip file' name the code for this program will be placed into function named backuptozip(this will make it easy to copy and paste the function organizing files
2,727
the programthe function will be called to perform the backup make your program look like this#python backuptozip py copies an entire folder and its contents into zip file whose filename increments import zipfileos def backuptozip(folder)back up the entire contents of "folderinto zip file folder os path abspath(foldermake sure folder is absolute figure out the filename this code should use based on what files already exist number while truezipfilename os path basename(folder'_str(numberzipif not os path exists(zipfilename)break number number todocreate the zip file todowalk the entire folder tree and compress the files in each folder print('done 'backuptozip(' :\\delicious'do the basics firstadd the shebang (#!linedescribe what the program doesand import the zipfile and os modules define backuptozip(function that takes just one parameterfolder this parameter is string path to the folder whose contents should be backed up the function will determine what filename to use for the zip file it will createthen the function will create the filewalk the folder folderand add each of the subfolders and files to the zip file write todo comments for these steps in the source code to remind yourself to do them later the first partnaming the zip fileuses the base name of the absolute path of folder if the folder being backed up is :\deliciousthe zip file' name should be delicious_n zipwhere is the first time you run the programn is the second timeand so on you can determine what should be by checking whether delicious_ zip already existsthen checking whether delicious_ zip already existsand so on use variable named number for and keep incrementing it inside the loop that calls os path exists(to check whether the file exists the first nonexistent filename found will cause the loop to breaksince it will have found the filename of the new zip
2,728
next let' create the zip file make your program look like the following#python backuptozip py copies an entire folder and its contents into zip file whose filename increments --snip-while truezipfilename os path basename(folder'_str(numberzipif not os path exists(zipfilename)break number number create the zip file print( 'creating {zipfilename'backupzip zipfile zipfile(zipfilename' 'todowalk the entire folder tree and compress the files in each folder print('done 'backuptozip(' :\\delicious'now that the new zip file' name is stored in the zipfilename variableyou can call zipfile zipfile(to actually create the zip file be sure to pass 'was the second argument so that the zip file is opened in write mode step walk the directory tree and add to the zip file now you need to use the os walk(function to do the work of listing every file in the folder and its subfolders make your program look like the following#python backuptozip py copies an entire folder and its contents into zip file whose filename increments --snip-walk the entire folder tree and compress the files in each folder for foldernamesubfoldersfilenames in os walk(folder)print( 'adding files in {foldername'add the current folder to the zip file backupzip write(foldernameadd all the files in this folder to the zip file for filename in filenamesnewbase os path basename(folder'_if filename startswith(newbaseand filename endswith(zip')continue don' back up the backup zip files backupzip write(os path join(foldernamefilename)backupzip close(organizing files
2,729
backuptozip(' :\\delicious'you can use os walk(in for loop and on each iteration it will return the iteration' current folder namethe subfolders in that folderand the filenames in that folder in the for loopthe folder is added to the zip file the nested for loop can go through each filename in the filenames list each of these is added to the zip fileexcept for previously made backup zips when you run this programit will produce output that will look something like thiscreating delicious_ zip adding files in :\delicious adding files in :\delicious\cats adding files in :\delicious\waffles adding files in :\delicious\walnut adding files in :\delicious\walnut\waffles done the second time you run itit will put all the files in :\delicious into zip file named delicious_ zipand so on ideas for similar programs you can walk directory tree and add files to compressed zip archives in several other programs for exampleyou can write programs that do the followingwalk directory tree and archive just files with certain extensionssuch as txt or pyand nothing else walk directory tree and archive every file except the txt and py ones find the folder in directory tree that has the greatest number of files or the folder that uses the most disk space summary even if you are an experienced computer useryou probably handle files manually with the mouse and keyboard modern file explorers make it easy to work with few files but sometimes you'll need to perform task that would take hours using your computer' file explorer the os and shutil modules offer functions for copyingmovingrenamingand deleting files when deleting filesyou might want to use the send trash module to move files to the recycle bin or trash rather than permanently deleting them and when writing programs that handle files
2,730
rename/delete and add print(call instead so you can run the program and verify exactly what it will do often you will need to perform these operations not only on files in one folder but also on every folder in that folderevery folder in those foldersand so on the os walk(function handles this trek across the folders for you so that you can concentrate on what your program needs to do with the files in them the zipfile module gives you way of compressing and extracting files in zip archives through python combined with the file-handling functions of os and shutilzipfile makes it easy to package up several files from anywhere on your hard drive these zip files are much easier to upload to websites or send as email attachments than many separate files previous of this book have provided source code for you to copy but when you write your own programsthey probably won' come out perfectly the first time the next focuses on some python modules that will help you analyze and debug your programs so that you can quickly get them working correctly practice questions what is the difference between shutil copy(and shutil copytree()what function is used to rename fileswhat is the difference between the delete functions in the send trash and shutil moduleszipfile objects have close(method just like file objectsclose(method what zipfile method is equivalent to file objectsopen(methodpractice projects for practicewrite programs to do the following tasks selective copy write program that walks through folder tree and searches for files with certain file extension (such as pdf or jpgcopy these files from whatever location they are in to new folder deleting unneeded files it' not uncommon for few unneeded but humongous files or folders to take up the bulk of the space on your hard drive if you're trying to free up room on your computeryou'll get the most bang for your buck by deleting the most massive of the unwanted files but first you have to find them organizing files
2,731
mb (remember that to get file' sizeyou can use os path getsize(from the os module print these files with their absolute path to the screen filling in the gaps write program that finds all files with given prefixsuch as spam txtspam txtand so onin single folder and locates any gaps in the numbering (such as if there is spam txt and spam txt but no spam txthave the program rename all the later files to close this gap as an added challengewrite another program that can insert gaps into numbered files so that new file can be added
2,732
debugging now that you know enough to write more complicated programsyou may start finding not-so-simple bugs in them this covers some tools and techniques for finding the root cause of bugs in your program to help you fix bugs faster and with less effort to paraphrase an old joke among programmerswriting code accounts for percent of programming debugging code accounts for the other percent your computer will do only what you tell it to doit won' read your mind and do what you intended it to do even professional programmers create bugs all the timeso don' feel discouraged if your program has problem fortunatelythere are few tools and techniques to identify what exactly your code is doing and where it' going wrong firstyou will look at logging and assertionstwo features that can help you detect bugs early in generalthe earlier you catch bugsthe easier they will be to fix
2,733
feature of mu that executes program one instruction at timegiving you chance to inspect the values in variables while your code runsand track how the values change over the course of your program this is much slower than running the program at full speedbut it is helpful to see the actual values in program while it runsrather than deducing what the values might be from the source code raising exceptions python raises an exception whenever it tries to execute invalid code in you read about how to handle python' exceptions with try and except statements so that your program can recover from exceptions that you anticipated but you can also raise your own exceptions in your code raising an exception is way of saying"stop running the code in this function and move the program execution to the except statement exceptions are raised with raise statement in codea raise statement consists of the followingthe raise keyword call to the exception(function string with helpful error message passed to the exception(function for exampleenter the following into the interactive shellraise exception('this is the error message 'traceback (most recent call last)file ""line in raise exception('this is the error message 'exceptionthis is the error message if there are no try and except statements covering the raise statement that raised the exceptionthe program simply crashes and displays the exception' error message often it' the code that calls the functionrather than the function itselfthat knows how to handle an exception that means you will commonly see raise statement inside function and the try and except statements in the code calling the function for exampleopen new file editor tabenter the following codeand save the program as boxprint pydef boxprint(symbolwidthheight)if len(symbol! raise exception('symbol must be single character string 'if width < raise exception('width must be greater than '
2,734
raise exception('height must be greater than 'print(symbol widthfor in range(height )print(symbol ((width )symbolprint(symbol widthfor symwh in (('*' )(' ' )(' ' )('zz' ))tryboxprint(symwhexcept exception as errprint('an exception happenedstr(err)you can view the execution of this program at here we've defined boxprint(function that takes charactera widthand heightand uses the character to make little picture of box with that width and height this box shape is printed to the screen say we want the character to be single characterand the width and height to be greater than we add if statements to raise exceptions if these requirements aren' satisfied laterwhen we call boxprint(with various argumentsour try/except will handle invalid arguments this program uses the except exception as err form of the except statement if an exception object is returned from boxprint(uvthis except statement will store it in variable named err we can then convert the exception object to string by passing it to str(to produce user-friendly error message when you run this boxprint pythe output will look like this******oooooooooooooooooooo oooooooooooooooooooo an exception happenedwidth must be greater than an exception happenedsymbol must be single character string using the try and except statementsyou can handle errors more gracefully instead of letting the entire program crash getting the traceback as string when python encounters an errorit produces treasure trove of error information called the traceback the traceback includes the error messagethe line number of the line that caused the errorand the sequence of the function calls that led to the error this sequence of calls is called the call stack debugging
2,735
save it as errorexample pydef spam()bacon(def bacon()raise exception('this is the error message 'spam(when you run errorexample pythe output will look like thistraceback (most recent call last)file "errorexample py"line in spam(file "errorexample py"line in spam bacon(file "errorexample py"line in bacon raise exception('this is the error message 'exceptionthis is the error message from the tracebackyou can see that the error happened on line in the bacon(function this particular call to bacon(came from line in the spam(functionwhich in turn was called on line in programs where functions can be called from multiple placesthe call stack can help you determine which call led to the error python displays the traceback whenever raised exception goes unhandled but you can also obtain it as string by calling traceback format_exc(this function is useful if you want the information from an exception' traceback but also want an except statement to gracefully handle the exception you will need to import python' traceback module before calling this function for exampleinstead of crashing your program right when an exception occursyou can write the traceback information to text file and keep your program running you can look at the text file laterwhen you're ready to debug your program enter the following into the interactive shellimport traceback tryraise exception('this is the error message 'excepterrorfile open('errorinfo txt'' 'errorfile write(traceback format_exc()errorfile close(print('the traceback info was written to errorinfo txt ' the traceback info was written to errorinfo txt
2,736
traceback (most recent call last)file ""line in exceptionthis is the error message in "loggingon page you'll learn how to use the logging modulewhich is more effective than simply writing this error information to text files assertions an assertion is sanity check to make sure your code isn' doing something obviously wrong these sanity checks are performed by assert statements if the sanity check failsthen an assertionerror exception is raised in codean assert statement consists of the followingthe assert keyword condition (that isan expression that evaluates to true or falsea comma string to display when the condition is false in plain englishan assert statement says" assert that the condition holds trueand if notthere is bug somewhereso immediately stop the program for exampleenter the following into the interactive shellages [ ages sort(ages [ assert ages[ <ages[- assert that the first age is <the last age the assert statement here asserts that the first item in ages should be less than or equal to the last one this is sanity checkif the code in sort(is bug-free and did its jobthen the assertion would be true because the ages[ <ages[- expression evaluates to truethe assert statement does nothing howeverlet' pretend we had bug in our code say we accidentally called the reverse(list method instead of the sort(list method when we enter the following in the interactive shellthe assert statement raises an assertionerrorages [ ages reverse(ages [ assert ages[ <ages[- assert that the first age is <the last age debugging
2,737
file ""line in assertionerror unlike exceptionsyour code should not handle assert statements with try and exceptif an assert failsyour program should crash by "failing fastlike thisyou shorten the time between the original cause of the bug and when you first notice the bug this will reduce the amount of code you will have to check before finding the bug' cause assertions are for programmer errorsnot user errors assertions should only fail while the program is under developmenta user should never see an assertion error in finished program for errors that your program can run into as normal part of its operation (such as file not being found or the user entering invalid data)raise an exception instead of detecting it with an assert statement you shouldn' use assert statements in place of raising exceptionsbecause users can choose to turn off assertions if you run python script with python - myscript py instead of python myscript pypython will skip assert statements users might disable assertions when they're developing program and need to run it in production setting that requires peak performance (thoughin many casesthey'll leave assertions enabled even then assertions also aren' replacement for comprehensive testing for instanceif the previous ages example was set to [ ]then the assert ages[ <ages[- assertion wouldn' notice that the list was unsortedbecause it just happened to have first age that was less than or equal to the last agewhich is the only thing the assertion checked for using an assertion in traffic light simulation say you're building traffic light simulation program the data structure representing the stoplights at an intersection is dictionary with keys 'nsand 'ew'for the stoplights facing north-south and east-westrespectively the values at these keys will be one of the strings 'green''yellow'or 'redthe code would look something like thismarket_ nd {'ns''green''ew''red'mission_ th {'ns''red''ew''green'these two variables will be for the intersections of market street and nd streetand mission street and th street to start the projectyou want to write switchlights(functionwhich will take an intersection dictionary as an argument and switch the lights at firstyou might think that switchlights(should simply switch each light to the next color in the sequenceany 'greenvalues should change to 'yellow''yellowvalues should change to 'red'and 'redvalues should change to 'greenthe code to implement this idea might look like thisdef switchlights(stoplight)for key in stoplight keys()
2,738
stoplight[key'yellowelif stoplight[key='yellow'stoplight[key'redelif stoplight[key='red'stoplight[key'greenswitchlights(market_ ndyou may already see the problem with this codebut let' pretend you wrote the rest of the simulation codethousands of lines longwithout noticing it when you finally do run the simulationthe program doesn' crash--but your virtual cars dosince you've already written the rest of the programyou have no idea where the bug could be maybe it' in the code simulating the cars or in the code simulating the virtual drivers it could take hours to trace the bug back to the switchlights(function but if while writing switchlights(you had added an assertion to check that at least one of the lights is always redyou might have included the following at the bottom of the functionassert 'redin stoplight values()'neither light is redstr(stoplightwith this assertion in placeyour program would crash with this error messagetraceback (most recent call last)file "carsim py"line in switchlights(market_ ndfile "carsim py"line in switchlights assert 'redin stoplight values()'neither light is redstr(stoplightassertionerrorneither light is red{'ns''yellow''ew''green'the important line here is the assertionerror while your program crashing is not idealit immediately points out that sanity check failedneither direction of traffic has red lightmeaning that traffic could be going both ways by failing fast early in the program' executionyou can save yourself lot of future debugging effort logging if you've ever put print(statement in your code to output some variable' value while your program is runningyou've used form of logging to debug your code logging is great way to understand what' happening in your program and in what order it' happening python' logging module makes it easy to create record of custom messages that you write these log messages will describe when the program execution has reached the logging debugging
2,739
on the other handa missing log message indicates part of the code was skipped and never executed using the logging module to enable the logging module to display log messages on your screen as your program runscopy the following to the top of your program (but under the #python shebang line)import logging logging basicconfig(level=logging debugformat=%(asctime) %(message) '%(levelnameyou don' need to worry too much about how this worksbut basicallywhen python logs an eventit creates logrecord object that holds information about that event the logging module' basicconfig(function lets you specify what details about the logrecord object you want to see and how you want those details displayed say you wrote function to calculate the factorial of number in mathematicsfactorial is or factorial is or , open new file editor tab and enter the following code it has bug in itbut you will also enter several log messages to help yourself figure out what is going wrong save the program as factoriallog py import logging logging basicconfig(level=logging debugformat='%(asctime) %(message) 'logging debug('start of program'%(levelname) def factorial( )logging debug('start of factorial(% %%)( )total for in range( )total * logging debug(' is str( 'total is str(total)logging debug('end of factorial(% %%)( )return total print(factorial( )logging debug('end of program'herewe use the logging debug(function when we want to print log information this debug(function will call basicconfig()and line of information will be printed this information will be in the format we specified in basicconfig(and will include the messages we passed to debug(the print(factorial( )call is part of the original programso the result is displayed even if logging messages are disabled
2,740
: : , debug start of program : : , debug start of factorial( : : , debug is total is : : , debug is total is : : , debug is total is : : , debug is total is : : , debug is total is : : , debug is total is : : , debug end of factorial( : : , debug end of program the factorial(function is returning as the factorial of which isn' right the for loop should be multiplying the value in total by the numbers from to but the log messages displayed by logging debug(show that the variable is starting at instead of since zero times anything is zerothe rest of the iterations also have the wrong value for total logging messages provide trail of breadcrumbs that can help you figure out when things started to go wrong change the for in range( )line to for in range( ):and run the program again the output will look like this : : , debug start of program : : , debug start of factorial( : : , debug is total is : : , debug is total is : : , debug is total is : : , debug is total is : : , debug is total is : : , debug end of factorial( : : , debug end of program the factorial( call correctly returns the log messages showed what was going on inside the loopwhich led straight to the bug you can see that the logging debug(calls printed out not just the strings passed to them but also timestamp and the word debug don' debug with the print(function typing import logging and logging basicconfig(level=logging debugformat'%(asctime) %(levelname) %(message) 'is somewhat unwieldy you may want to use print(calls insteadbut don' give in to this temptationonce you're done debuggingyou'll end up spending lot of time removing print(calls from your code for each log message you might even accidentally remove some print(calls that were being used for nonlog messages the nice thing about log messages is that you're free to fill your program debugging
2,741
single logging disable(logging criticalcall unlike print()the logging module makes it easy to switch between showing and hiding log messages log messages are intended for the programmernot the user the user won' care about the contents of some dictionary value you need to see to help with debugginguse log message for something like that for messages that the user will want to seelike file not found or invalid inputplease enter numberyou should use print(call you don' want to deprive the user of useful information after you've disabled log messages logging levels logging levels provide way to categorize your log messages by importance there are five logging levelsdescribed in table - from least to most important messages can be logged at each level using different logging function table - logging levels in python level logging function description debug logging debug(the lowest level used for small details usually you care about these messages only when diagnosing problems info logging info(used to record information on general events in your program or confirm that things are working at their point in the program warning logging warning(used to indicate potential problem that doesn' prevent the program from working but might do so in the future error logging error(used to record an error that caused the program to fail to do something critical logging critical(the highest level used to indicate fatal error that has caused or is about to cause the program to stop running entirely your logging message is passed as string to these functions the logging levels are suggestions ultimatelyit is up to you to decide which category your log message falls into enter the following into the interactive shellimport logging logging basicconfig(level=logging debugformat=%(asctime) %(levelname) %(message) 'logging debug('some debugging details ' : : , debug some debugging details logging info('the logging module is working ' : : , info the logging module is working logging warning('an error message is about to be logged ' : : , warning an error message is about to be logged
2,742
: : , error an error has occurred logging critical('the program is unable to recover!' : : , critical the program is unable to recoverthe benefit of logging levels is that you can change what priority of logging message you want to see passing logging debug to the basicconfig(function' level keyword argument will show messages from all the logging levels (debug being the lowest levelbut after developing your program some moreyou may be interested only in errors in that caseyou can set basicconfig()' level argument to logging error this will show only error and critical messages and skip the debuginfoand warning messages disabling logging after you've debugged your programyou probably don' want all these log messages cluttering the screen the logging disable(function disables these so that you don' have to go into your program and remove all the logging calls by hand you simply pass logging disable( logging leveland it will suppress all log messages at that level or lower so if you want to disable logging entirelyjust add logging disable(logging criticalto your program for exampleenter the following into the interactive shellimport logging logging basicconfig(level=logging infoformat=%(asctime) %(levelname) %(message) 'logging critical('critical errorcritical error!' : : , critical critical errorcritical errorlogging disable(logging criticallogging critical('critical errorcritical error!'logging error('errorerror!'since logging disable(will disable all messages after ityou will probably want to add it near the import logging line of code in your program this wayyou can easily find it to comment out or uncomment that call to enable or disable logging messages as needed logging to file instead of displaying the log messages to the screenyou can write them to text file the logging basicconfig(function takes filename keyword argumentlike soimport logging logging basicconfig(filename='myprogramlog txt'level=logging debugformat=%(asctime) %(levelname) %(message) 'the log messages will be saved to myprogramlog txt while logging messages are helpfulthey can clutter your screen and make it hard to read debugging
2,743
screen clear and store the messages so you can read them after running the program you can open this text file in any text editorsuch as notepad or textedit mu' debugger the debugger is feature of the mu editoridleand other editor software that allows you to execute your program one line at time the debugger will run single line of code and then wait for you to tell it to continue by running your program "under the debuggerlike thisyou can take as much time as you want to examine the values in the variables at any given point during the program' lifetime this is valuable tool for tracking down bugs to run program under mu' debuggerclick the debug button in the top row of buttonsnext to the run button along with the usual output pane at the bottomthe debug inspector pane will open along the right side of the window this pane lists the current value of variables in your program in figure - the debugger has paused the execution of the program just before it would have run the first line of code you can see this line highlighted in the file editor figure - mu running program under the debugger debugging mode also adds the following new buttons to the top of the editorcontinuestep overstep inand step out the usual stop button is also available
2,744
clicking the continue button will cause the program to execute normally until it terminates or reaches breakpoint ( will describe breakpoints later in this if you are done debugging and want the program to continue normallyclick the continue button step in clicking the step in button will cause the debugger to execute the next line of code and then pause again if the next line of code is function callthe debugger will "step intothat function and jump to the first line of code of that function step over clicking the step over button will execute the next line of codesimilar to the step in button howeverif the next line of code is function callthe step over button will "step overthe code in the function the function' code will be executed at full speedand the debugger will pause as soon as the function call returns for exampleif the next line of code calls spam(function but you don' really care about code inside this functionyou can click step over to execute the code in the function at normal speedand then pause when the function returns for this reasonusing the over button is more common than using the step in button step out clicking the step out button will cause the debugger to execute lines of code at full speed until it returns from the current function if you have stepped into function call with the step in button and now simply want to keep executing instructions until you get back outclick the out button to "step outof the current function call stop if you want to stop debugging entirely and not bother to continue executing the rest of the programclick the stop button the stop button will immediately terminate the program debugging number adding program open new file editor tab and enter the following codeprint('enter the first number to add:'first input(print('enter the second number to add:'second input(print('enter the third number to add:'third input(print('the sum is first second thirddebugging
2,745
enabled the program will output something like thisenter the first number to add enter the second number to add enter the third number to add the sum is the program hasn' crashedbut the sum is obviously wrong run the program againthis time under the debugger when you click the debug buttonthe program pauses on line which is the line of code it is about to execute mu should look like figure - click the step over button once to execute the first print(call you should use step over instead of step in heresince you don' want to step into the code for the print(function (although mu should prevent the debugger from entering python' built-in functions the debugger moves on to line and highlights line in the file editoras shown in figure - this shows you where the program execution currently is figure - the mu editor window after clicking step over click step over again to execute the input(function call the highlighting will go away while mu waits for you to type something for the input(call into the output pane enter and press enter the highlighting will return keep clicking step overand enter and as the next two numbers when the debugger reaches line the final print(call in the programthe mu editor window should look like figure -
2,746
variables are set to strings instead of integerscausing the bug in the debug inspector paneyou should see that the firstsecondand third variables are set to string values ' '' 'and ' instead of integer values and when the last line is executedpython concatenates these strings instead of adding the numbers togethercausing the bug stepping through the program with the debugger is helpful but can also be slow often you'll want the program to run normally until it reaches certain line of code you can configure the debugger to do this with breakpoints breakpoints breakpoint can be set on specific line of code and forces the debugger to pause whenever the program execution reaches that line open new file editor tab and enter the following programwhich simulates flipping coin , times save it as coinflip py import random heads for in range( )if random randint( = heads heads if = print('halfway done!'print('heads came up str(headstimes 'the random randint( call will return half of the time and the other half of the time this can be used to simulate / coin flip where represents heads when you run this program without the debuggerit quickly outputs something like the followinghalfway doneheads came up times debugging
2,747
the step over button thousands of times before the program terminated if you were interested in the value of heads at the halfway point of the program' executionwhen of , coin flips have been completedyou could instead just set breakpoint on the line print('halfway done!'to set breakpointclick the line number in the file editor to cause red dot to appearmarking the breakpoint like in figure - figure - setting breakpoint causes red dot (circledto appear next to the line number you don' want to set breakpoint on the if statement linesince the if statement is executed on every single iteration through the loop when you set the breakpoint on the code in the if statementthe debugger breaks only when the execution enters the if clause the line with the breakpoint will have red dot next to it when you run the program under the debuggerit will start in paused state at the first lineas usual but if you click continuethe program will run at full speed until it reaches the line with the breakpoint set on it you can then click continuestep overstep inor step out to continue as normal if you want to remove breakpointclick the line number again the red dot will go awayand the debugger will not break on that line in the future summary assertionsexceptionsloggingand the debugger are all valuable tools to find and prevent bugs in your program assertions with the python assert statement are good way to implement "sanity checksthat give you an early warning when necessary condition doesn' hold true assertions are only for errors that the program shouldn' try to recover from and should fail fast otherwiseyou should raise an exception
2,748
running and is much more convenient to use than the print(function because of its different logging levels and ability to log to text file the debugger lets you step through your program one line at time alternativelyyou can run your program at normal speed and have the debugger pause execution whenever it reaches line with breakpoint set using the debuggeryou can see the state of any variable' value at any point during the program' lifetime these debugging tools and techniques will help you write programs that work accidentally introducing bugs into your code is fact of lifeno matter how many years of coding experience you have practice questions write an assert statement that triggers an assertionerror if the variable spam is an integer less than write an assert statement that triggers an assertionerror if the variables eggs and bacon contain strings that are the same as each othereven if their cases are different (that is'helloand 'helloare considered the sameand 'goodbyeand 'goodbyeare also considered the same write an assert statement that always triggers an assertionerror what are the two lines that your program must have in order to be able to call logging debug() what are the two lines that your program must have in order to have logging debug(send logging message to file named programlog txt what are the five logging levels what line of code can you add to disable all logging messages in your program why is using logging messages better than using print(to display the same message what are the differences between the step overstep inand step out buttons in the debugger after you click continuewhen will the debugger stop what is breakpoint how do you set breakpoint on line of code in mudebugging
2,749
for practicewrite program that does the following debugging coin toss the following program is meant to be simple coin toss guessing game the player gets two guesses (it' an easy gamehoweverthe program has several bugs in it run through the program few times to find the bugs that keep the program from working correctly import random guess 'while guess not in ('heads''tails')print('guess the coin tossenter heads or tails:'guess input(toss random randint( is tails is heads if toss =guessprint('you got it!'elseprint('nopeguess again!'guesss input(if toss =guessprint('you got it!'elseprint('nope you are really bad at this game '
2,750
web scr aping in those rareterrifying moments when ' without wi-fii realize just how much of what do on the computer is really what do on the internet out of sheer habit 'll find myself trying to check emailread friendstwitter feedsor answer the question"did kurtwood smith have any major roles before he was in the original robocop?" since so much work on computer involves going on the internetit' be great if your programs could get online web scraping is the term for using program to download and process content from the web for examplegoogle runs many web scraping programs to index web pages for the answer is no
2,751
make it easy to scrape web pages in python comes with python and opens browser to specific page requests downloads files and web pages from the internet bs parses htmlthe format that web pages are written in selenium launches and controls web browser the selenium module is able to fill in forms and simulate mouse clicks in this browser webbrowser projectmapit py with the webbrowser module the webbrowser module' open(function can launch new browser to specified url enter the following into the interactive shellimport webbrowser webbrowser open(' web browser tab will open to the url this is about the only thing the webbrowser module can do even sothe open(function does make some interesting things possible for exampleit' tedious to copy street address to the clipboard and bring up map of it on google maps you could take few steps out of this task by writing simple script to automatically launch the map in your browser using the contents of your clipboard this wayyou only have to copy the address to clipboard and run the scriptand the map will be loaded for you this is what your program does gets street address from the command line arguments or clipboard opens the web browser to the google maps page for the address this means your code will need to do the following read the command line arguments from sys argv read the clipboard contents call the webbrowser open(function to open the web browser open new file editor tab and save it as mapit py step figure out the url based on the instructions in appendix bset up mapit py so that when you run it from the command linelike so :\mapit valencia stsan franciscoca the script will use the command line arguments instead of the clipboard if there are no command line argumentsthen the program will know to use the contents of the clipboard
2,752
when you load addressthe url in the address bar looks something like thisgoogle com/maps/place/ +valencia+st/@ ,- , /data=! ! ! ! ! dadc : xc bb the address is in the urlbut there' lot of additional text there as well websites often add extra data to urls to help track visitors or customize sites but if you try just going to valencia+st+san+francisco+ca/you'll find that it still brings up the correct page so your program can be set to open web browser to google com/maps/place/your_address_string(where your_address_string is the address you want to mapstep handle the command line arguments make your code look like this#python mapit py launches map in the browser using an address from the command line or clipboard import webbrowsersys if len(sys argv get address from command line address join(sys argv[ :]todoget address from clipboard after the program' #shebang lineyou need to import the webbrowser module for launching the browser and import the sys module for reading the potential command line arguments the sys argv variable stores list of the program' filename and command line arguments if this list has more than just the filename in itthen len(sys argvevaluates to an integer greater than meaning that command line arguments have indeed been provided command line arguments are usually separated by spacesbut in this caseyou want to interpret all of the arguments as single string since sys argv is list of stringsyou can pass it to the join(methodwhich returns single string value you don' want the program name in this stringso instead of sys argvyou should pass sys argv[ :to chop off the first element of the array the final string that this expression evaluates to is stored in the address variable if you run the program by entering this into the command line mapit valencia stsan franciscoca the sys argv variable will contain this list value['mapit py'' ''valencia''st''san''francisco''ca'' 'the address variable will contain the string ' valencia stsan franciscoca web scraping
2,753
make your code look like the following#python mapit py launches map in the browser using an address from the command line or clipboard import webbrowsersyspyperclip if len(sys argv get address from command line address join(sys argv[ :]elseget address from clipboard address pyperclip paste(webbrowser open('if there are no command line argumentsthe program will assume the address is stored on the clipboard you can get the clipboard content with pyperclip paste(and store it in variable named address finallyto launch web browser with the google maps urlcall webbrowser open(while some of the programs you write will perform huge tasks that save you hoursit can be just as satisfying to use program that conveniently saves you few seconds each time you perform common tasksuch as getting map of an address table - compares the steps needed to display map with and without mapit py table - getting map with and without mapit py manually getting map using mapit py highlight the address copy the address open the web browser go to click the address text field paste the address press enter highlight the address copy the address run mapit py see how mapit py makes this task less tediousideas for similar programs as long as you have urlthe webbrowser module lets users cut out the step of opening the browser and directing themselves to website other programs could use this functionality to do the following open all links on page in separate browser tabs open the browser to the url for your local weather open several social network sites that you regularly check
2,754
the requests module lets you easily download files from the web without having to worry about complicated issues such as network errorsconnection problemsand data compression the requests module doesn' come with pythonso you'll have to install it first from the command linerun pip install --user requests (appendix has additional details on how to install third-party modules the requests module was written because python' urllib module is too complicated to use in facttake permanent marker and black out this entire paragraph forget ever mentioned urllib if you need to download things from the webjust use the requests module nextdo simple test to make sure the requests module installed itself correctly enter the following into the interactive shellimport requests if no error messages show upthen the requests module has been successfully installed downloading web page with the requests get(function the requests get(function takes string of url to download by calling type(on requests get()' return valueyou can see that it returns response objectwhich contains the response that the web server gave for your request 'll explain the response object in more detail laterbut for nowenter the following into the interactive shell while your computer is connected to the internetimport requests res requests get(type(resres status_code =requests codes ok true len(res text print(res text[: ]the project gutenberg ebook of romeo and julietby william shakespeare this ebook is for the use of anyone anywhere at no cost and with almost no restrictions whatsoever you may copy itgive it away or re-use it under the terms of the proje the url goes to text web page for the entire play of romeo and julietprovided on this book' site you can tell that the request for this web page succeeded by checking the status_code attribute of the response object if it is equal to the value of requests codes okthen everything went fine (incidentallythe status code for "okin the http protocol is you may already be familiar with the status code for "not found "web scraping
2,755
if the request succeededthe downloaded web page is stored as string in the response object' text variable this variable holds large string of the entire playthe call to len(res textshows you that it is more than , characters long finallycalling print(res text[: ]displays only the first characters if the request failed and displayed an error messagelike "failed to establish new connectionor "max retries exceeded,then check your internet connection connecting to servers can be quite complicatedand can' give full list of possible problems here you can find common causes of your error by doing web search of the error message in quotes checking for errors as you've seenthe response object has status_code attribute that can be checked against requests codes ok ( variable that has the integer value to see whether the download succeeded simpler way to check for success is to call the raise_for_status(method on the response object this will raise an exception if there was an error downloading the file and will do nothing if the download succeeded enter the following into the interactive shellres requests get(res raise_for_status(traceback (most recent call last)file ""line in file " :\users\al\appdata\local\programs\python\python \lib\site-packages\requests\models py"line in raise_for_status raise httperror(http_error_msgresponse=selfrequests exceptions httperror client errornot found for urlcom/page_that_does_not_exist html the raise_for_status(method is good way to ensure that program halts if bad download occurs this is good thingyou want your program to stop as soon as some unexpected error happens if failed download isn' deal breaker for your programyou can wrap the raise_for_status(line with try and except statements to handle this error case without crashing import requests res requests get('tryres raise_for_status(except exception as excprint('there was problem% (exc)this raise_for_status(method call causes the program to output the followingthere was problem client errornot found for urlinventwithpython com/page_that_does_not_exist html
2,756
sure that the download has actually worked before your program continues saving downloaded files to the hard drive from hereyou can save the web page to file on your hard drive with the standard open(function and write(method there are some slight differencesthough firstyou must open the file in write binary mode by passing the string 'wbas the second argument to open(even if the page is in plaintext (such as the romeo and juliet text you downloaded earlier)you need to write binary data instead of text data in order to maintain the unicode encoding of the text to write the web page to fileyou can use for loop with the response object' iter_content(method import requests res requests get(res raise_for_status(playfile open('romeoandjuliet txt''wb'for chunk in res iter_content( )playfile write(chunk playfile close(the iter_content(method returns "chunksof the content on each iteration through the loop each chunk is of the bytes data typeand you get to specify how many bytes each chunk will contain one hundred thousand bytes is generally good sizeso pass as the argument to iter_content(the file romeoandjuliet txt will now exist in the current working directory note that while the filename on the website was rj txtthe file on your hard drive has different filename the requests module simply handles downloading the contents of web pages once the page is downloadedit is simply data in your program even if you were to lose your internet unicode ncodings unicode encodings are beyond the scope of this bookbut you can learn more about them from these web pagesjoel on softwarethe absolute minimum every software developer absolutelypositively must know about unicode and character sets (no excuses!)pragmatic unicodeweb scraping
2,757
on your computer the write(method returns the number of bytes written to the file in the previous examplethere were , bytes in the first chunkand the remaining part of the file needed only , bytes to reviewhere' the complete process for downloading and saving file call requests get(to download the file call open(with 'wbto create new file in write binary mode loop over the response object' iter_content(method call write(on each iteration to write the content to the file call close(to close the file that' all there is to the requests modulethe for loop and iter_content(stuff may seem complicated compared to the open()/write()/close(workflow you've been using to write text filesbut it' to ensure that the requests module doesn' eat up too much memory even if you download massive files you can learn about the requests module' other features from requests readthedocs orghtml before you pick apart web pagesyou'll learn some html basics you'll also see how to access your web browser' powerful developer toolswhich will make scraping information from the web much easier resources for learning html hypertext markup language (htmlis the format that web pages are written in this assumes you have some basic experience with htmlbut if you need beginner tutoriali suggest one of the following sitesa quick refresher in case it' been while since you've looked at any htmlhere' quick overview of the basics an html file is plaintext file with the html file extension the text in these files is surrounded by tagswhich are words enclosed in angle brackets the tags tell the browser how to format the web page starting tag and closing tag can enclose some text to form an element the text (or inner htmlis the content between the starting and closing tags for examplethe following html will display helloworldin the browserwith hello in boldhelloworld
2,758
figure - helloworldrendered in the browser the opening tag says that the enclosed text will appear in bold the closing tags tells the browser where the end of the bold text is there are many different tags in html some of these tags have extra properties in the form of attributes within the angle brackets for examplethe tag encloses text that should be link the url that the text links to is determined by the href attribute here' an exampleal' free < href="this html will look like figure - in browser figure - the link rendered in the browser some elements have an id attribute that is used to uniquely identify the element in the page you will often instruct your programs to seek out an element by its id attributeso figuring out an element' id attribute using the browser' developer tools is common task in writing web scraping programs viewing the source html of web page you'll need to look at the html source of the web pages that your programs will work with to do thisright-click (or ctrl-click on macosany web page in your web browserand select view source or view page source to see the html text of the page (see figure - this is the text your browser actually receives the browser knows how to displayor renderthe web page from this html web scraping
2,759
highly recommend viewing the source html of some of your favorite sites it' fine if you don' fully understand what you are seeing when you look at the source you won' need html mastery to write simple web scraping programs--after allyou won' be writing your own websites you just need enough knowledge to pick out data from an existing site opening your browser' developer tools in addition to viewing web page' sourceyou can look through page' html using your browser' developer tools in chrome and internet explorer for windowsthe developer tools are already installedand you can press to make them appear (see figure - pressing again will make the developer tools disappear in chromeyou can also bring up the developer tools by selecting viewdeveloperdeveloper tools in macospressing option- will open chrome' developer tools
2,760
in firefoxyou can bring up the web developer tools inspector by pressing ctrlshift- on windows and linux or by pressing option- on macos the layout is almost identical to chrome' developer tools in safariopen the preferences windowand on the advanced pane check the show develop menu in the menu bar option after it has been enabledyou can bring up the developer tools by pressing option- after enabling or installing the developer tools in your browseryou can right-click any part of the web page and select inspect element from the context menu to bring up the html responsible for that part of the page this will be helpful when you begin to parse html for your web scraping programs don' use regul pre ssions to pa rse tml locating specific piece of html in string seems like perfect case for regular expressions howeveri advise you against it there are many different ways that html can be formatted and still be considered valid htmlbut trying to capture all these possible variations in regular expression can be tedious and error prone module developed specifically for parsing htmlsuch as bs will be less likely to result in bugs you can find an extended argument for why you shouldn' parse html with regular expressions at web scraping
2,761
once your program has downloaded web page using the requests moduleyou will have the page' html content as single string value now you need to figure out which part of the html corresponds to the information on the web page you're interested in this is where the browser' developer tools can help say you want to write program to pull weather forecast data from before writing any codedo little research if you visit the site and search for the zip codethe site will take you to page showing the forecast for that area what if you're interested in scraping the weather information for that zip coderight-click where it is on the page (or control-click on macosand select inspect element from the context menu that appears this will bring up the developer tools windowwhich shows you the html that produces this particular part of the web page figure - shows the developer tools open to the html of the nearest forecast note that if the repeat this process to inspect the new elements figure - inspecting the element that holds forecast text with the developer tools
2,762
forecast part of the web page is sunnywith high near west wind to mphwith gusts as high as mph this is exactly what you were looking forit seems that the forecast information is contained inside element with the forecast-text css class right-click on this element in the browser' developer consoleand from the context menu that appearsselect copy css selector this will copy string such as 'div row-odd:nth-child( div:nth-child( )to the clipboard you can use this string for beautiful soup' select(or selenium' find_element_by_css_selector(methodsas explained later in this now that you know what you're looking forthe beautiful soup module will help you find it in the string parsing html with the bs module beautiful soup is module for extracting information from an html page (and is much better for this purpose than regular expressionsthe beautiful soup module' name is bs (for beautiful soupversion to install ityou will need to run pip install --user beautifulsoup from the command line (check out appendix for instructions on installing thirdparty modules while beautifulsoup is the name used for installationto import beautiful soup you run import bs for this the beautiful soup examples will parse (that isanalyze and identify the parts ofan html file on the hard drive open new file editor tab in muenter the followingand save it as example html alternativelydownload it from the website title download my python book from my website learn python the easy wayby al sweigart as you can seeeven simple html file involves many different tags and attributesand matters quickly get confusing with complex websites thankfullybeautiful soup makes working with html much easier web scraping
2,763
the bs beautifulsoup(function needs to be called with string containing the html it will parse the bs beautifulsoup(function returns beautifulsoup object enter the following into the interactive shell while your computer is connected to the internetimport requestsbs res requests get(res raise_for_status(nostarchsoup bs beautifulsoup(res text'html parser'type(nostarchsoupthis code uses requests get(to download the main page from the no starch press website and then passes the text attribute of the response to bs beautifulsoup(the beautifulsoup object that it returns is stored in variable named nostarchsoup you can also load an html file from your hard drive by passing file object to bs beautifulsoup(along with second argument that tells beautiful soup which parser to use to analyze the html enter the following into the interactive shell (after making sure the example html file is in the working directory)examplefile open('example html'examplesoup bs beautifulsoup(examplefile'html parser'type(examplesoupthe 'html parserparser used here comes with python howeveryou can use the faster 'lxmlparser if you install the third-party lxml module follow the instructions in appendix to install this module by running pip install --user lxml forgetting to include this second argument will result in userwarningno parser was explicitly specified warning once you have beautifulsoup objectyou can use its methods to locate specific parts of an html document finding an element with the select(method you can retrieve web page element from beautifulsoup object by calling the select()method and passing string of css selector for the element you are looking for selectors are like regular expressionsthey specify pattern to look for--in this casein html pages instead of general text strings full discussion of css selector syntax is beyond the scope of this book (there' good selector tutorial in the resources at /automatestuff /)but here' short introduction to selectors table - shows examples of the most common css selector patterns
2,764
selector passed to the select(method will match soup select('div'all elements named soup select('#author'the element with an id attribute of author soup select(notice'all elements that use css class attribute named notice soup select('div span'all elements named that are within an element named soup select('div span'all elements named that are directly within an element named with no other element in between soup select('input[name]'all elements named that have name attribute with any value soup select('input[type="button"]'all elements named that have an attribute named type with value button the various selector patterns can be combined to make sophisticated matches for examplesoup select(' #author'will match any element that has an id attribute of authoras long as it is also inside element instead of writing the selector yourselfyou can also right-click on the element in your browser and select inspect element when the browser' developer console opensright-click on the element' html and select copy css selector to copy the selector string to the clipboard and paste it into your source code the select(method will return list of tag objectswhich is how beautiful soup represents an html element the list will contain one tag object for every match in the beautifulsoup object' html tag values can be passed to the str(function to show the html tags they represent tag values also have an attrs attribute that shows all the html attributes of the tag as dictionary using the example html file from earlierenter the following into the interactive shellimport bs examplefile open('example html'examplesoup bs beautifulsoup(examplefile read()'html parser'elems examplesoup select('#author'type(elemselems is list of tag objects len(elems type(elems[ ]str(elems[ ]the tag object as string 'al sweigartelems[ gettext('al sweigartelems[ attrs {'id''author'web scraping
2,765
html we use select('#author'to return list of all the elements with id="authorwe store this list of tag objects in the variable elemsand len(elemstells us there is one tag object in the listthere was one match calling gettext(on the element returns the element' textor inner html the text of an element is the content between the opening and closing tagsin this case'al sweigartpassing the element to str(returns string with the starting and closing tags and the element' text finallyattrs gives us dictionary with the element' attribute'id'and the value of the id attribute'authoryou can also pull all the elements from the beautifulsoup object enter this into the interactive shellpelems examplesoup select(' 'str(pelems[ ]'download my python book from my website pelems[ gettext('download my python book from my website str(pelems[ ]'learn python the easy way!pelems[ gettext('learn python the easy way!str(pelems[ ]'by al sweigartpelems[ gettext('by al sweigartthis timeselect(gives us list of three matcheswhich we store in pelems using str(on pelems[ ]pelems[ ]and pelems[ shows you each element as stringand using gettext(on each element shows you its text getting data from an element' attributes the get(method for tag objects makes it simple to access attribute values from an element the method is passed string of an attribute name and returns that attribute' value using example htmlenter the following into the interactive shellimport bs soup bs beautifulsoup(open('example html')'html parser'spanelem soup select('span')[ str(spanelem'al sweigartspanelem get('id''authorspanelem get('some_nonexistent_addr'=none true spanelem attrs {'id''author'
2,766
first matched element in spanelem passing the attribute name 'idto get(returns the attribute' value'authorprojectopening all search results whenever search topic on googlei don' look at just one search result at time by middle-clicking search result link (or clicking while holding ctrl) open the first several links in bunch of new tabs to read later search google often enough that this workflow--opening my browsersearching for topicand middle-clicking several links one by one--is tedious it would be nice if could simply type search term on the command line and have my computer automatically open browser with all the top search results in new tabs let' write script to do this with the search results page for the python package index at and duckduckgo often employ measures that make scraping their search results pages difficult this is what your program does gets search keywords from the command line arguments retrieves the search results page opens browser tab for each result this means your code will need to do the following read the command line arguments from sys argv fetch the search result page with the requests module find the links to each search result call the webbrowser open(function to open the web browser open new file editor tab and save it as searchpypi py step get the command line arguments and request the search page before coding anythingyou first need to know the url of the search result page by looking at the browser' address bar after doing searchyou can see that the result page has url like _term_herethe requests module can download this page and then you can use beautiful soup to find the search result links in the html finallyyou'll use the webbrowser module to open those links in browser tabs make your code look like the following#python searchpypi py opens several search results import requestssyswebbrowserbs web scraping
2,767
display text while downloading the search result page res requests get('join(sys argv[ :])res raise_for_status(todoretrieve top search result links todoopen browser tab for each result the user will specify the search terms using command line arguments when they launch the program these arguments will be stored as strings in list in sys argv step find all the results now you need to use beautiful soup to extract the top search result links from your downloaded html but how do you figure out the right selector for the jobfor exampleyou can' just search for all tagsbecause there are lots of links you don' care about in the html insteadyou must inspect the search result page with the browser' developer tools to try to find selector that will pick out only the links you want after doing search for beautiful soupyou can open the browser' developer tools and inspect some of the link elements on the page they can look complicatedsomething like pages of this< class="package -snippethref="hyperlink "view-source:/"/project/xml-parser/"it doesn' matter that the element looks incredibly complicated you just need to find the pattern that all the search result links have make your code look like the following#python searchpypi py opens several google results import requestssyswebbrowserbs --snip-retrieve top search result links soup bs beautifulsoup(res text'html parser'open browser tab for each result linkelems soup select(package-snippet'if you look at the elementsthoughthe search result links all have class="package-snippetlooking through the rest of the html sourceit looks like the package-snippet class is used only for search result links you don' have to know what the css class package-snippet is or what it does you're just going to use it as marker for the element you are looking for you can create beautifulsoup object from the downloaded page' html text and then use the selector package-snippetto find all elements that are within an element that has the package-snippet css class note that if the pypi website changes its layoutyou may need to update this program with new css selector string to pass to soup select(the rest of the program will still be up to date
2,768
finallywe'll tell the program to open web browser tabs for our results add the following to the end of your program#python searchpypi py opens several search results import requestssyswebbrowserbs --snip-open browser tab for each result linkelems soup select(package-snippet'numopen min( len(linkelems)for in range(numopen)urltoopen 'print('opening'urltoopenwebbrowser open(urltoopenby defaultyou open the first five search results in new tabs using the webbrowser module howeverthe user may have searched for something that turned up fewer than five results the soup select(call returns list of all the elements that matched your package-snippetselectorso the number of tabs you want to open is either or the length of this list (whichever is smallerthe built-in python function min(returns the smallest of the integer or float arguments it is passed (there is also built-in max(function that returns the largest argument it is passed you can use min(to find out whether there are fewer than five links in the list and store the number of links to open in variable named numopen then you can run through for loop by calling range(numopenon each iteration of the loopyou use webbrowser open(to open new tab in the web browser note that the href attribute' value in the returned elements do not have the initial now you can instantly open the first five pypi search results forsayboring stuff by running searchpypi boring stuff on the command line(see appendix for how to easily run programs on your operating system ideas for similar programs the benefit of tabbed browsing is that you can easily open links in new tabs to peruse later program that automatically opens several links at once can be nice shortcut to do the followingopen all the product pages after searching shopping site such as amazon open all the links to reviews for single product open the result links to photos after performing search on photo site such as flickr or imgur web scraping
2,769
blogs and other regularly updating websites usually have front page with the most recent post as well as previous button on the page that takes you to the previous post then that post will also have previous buttonand so oncreating trail from the most recent page to the first post on the site if you wanted copy of the site' content to read when you're not onlineyou could manually navigate over every page and save each one but this is pretty boring workso let' write program to do it instead xkcd is popular geek webcomic with website that fits this structure (see figure - the front page at guides the user back through prior comics downloading each comic by hand would take foreverbut you can write script to do this in couple of minutes figure - xkcd" webcomic of romancesarcasmmathand languagehere' what your program does loads the xkcd home page saves the comic image on that page follows the previous comic link repeats until it reaches the first comic this means your code will need to do the following download pages with the requests module find the url of the comic image for page using beautiful soup
2,770
download and save the comic image to the hard drive with iter_content(find the url of the previous comic linkand repeat open new file editor tab and save it as downloadxkcd py step design the program if you open the browser' developer tools and inspect the elements on the pageyou'll find the followingthe url of the comic' image file is given by the href attribute of an element the element is inside element the prev button has rel html attribute with the value prev the first comic' prev button links to the indicating that there are no more previous pages make your code look like the following#python downloadxkcd py downloads every single xkcd comic import requestsosbs url 'os makedirs('xkcd'exist_ok=truewhile not url endswith('#')tododownload the page starting url store comics in /xkcd todofind the url of the comic image tododownload the image todosave the image to /xkcd todoget the prev button' url print('done 'you'll have url variable that starts with the value 'and repeatedly update it (in for loopwith the url of the current page' prev link at every step in the loopyou'll download the comic at url you'll know to end the loop when url ends with '#you will download the image files to folder in the current working directory named xkcd the call os makedirs(ensures that this folder existsand the exist_ok=true keyword argument prevents the function from web scraping
2,771
just comments that outline the rest of your program step download the web page let' implement the code for downloading the page make your code look like the following#python downloadxkcd py downloads every single xkcd comic import requestsosbs url 'starting url os makedirs('xkcd'exist_ok=truestore comics in /xkcd while not url endswith('#')download the page print('downloading page % urlres requests get(urlres raise_for_status(soup bs beautifulsoup(res text'html parser'todofind the url of the comic image tododownload the image todosave the image to /xkcd todoget the prev button' url print('done 'firstprint url so that the user knows which url the program is about to downloadthen use the requests module' request get(function to download it as alwaysyou immediately call the response object' raise_for_status(method to throw an exception and end the program if something went wrong with the download otherwiseyou create beautifulsoup object from the text of the downloaded page step find and download the comic image make your code look like the following#python downloadxkcd py downloads every single xkcd comic import requestsosbs --snip-find the url of the comic image comicelem soup select('#comic img'
2,772
print('could not find comic image 'elsecomicurl 'https:comicelem[ get('src'download the image print('downloading image % (comicurl)res requests get(comicurlres raise_for_status(todosave the image to /xkcd todoget the prev button' url print('done 'from inspecting the xkcd home page with your developer toolsyou know that the element for the comic image is inside element with the id attribute set to comicso the selector '#comic imgwill get you the correct element from the beautifulsoup object few xkcd pages have special content that isn' simple image file that' fineyou'll just skip those if your selector doesn' find any elementsthen soup select('#comic img'will return blank list when that happensthe program can just print an error message and move on without downloading the image otherwisethe selector will return list containing one element you can get the src attribute from this element and pass it to requests get(to download the comic' image file step save the image and find the previous comic make your code look like the following#python downloadxkcd py downloads every single xkcd comic import requestsosbs --snip-save the image to /xkcd imagefile open(os path join('xkcd'os path basename(comicurl))'wb'for chunk in res iter_content( )imagefile write(chunkimagefile close(get the prev button' url prevlink soup select(' [rel="prev"]')[ url 'print('done 'web scraping
2,773
you need to write this image data to file on the hard drive you'll need filename for the local image file to pass to open(the comicurl will have value like '_explanation png'--which you might have noticed looks lot like file path and in factyou can call os path basename(with comicurland it will return just the last part of the url'heartbleed_explanation pngyou can use this as the filename when saving the image to your hard drive you join this name with the name of your xkcd folder using os path join(so that your program uses backslashes (\on windows and forward slashes (/on macos and linux now that you finally have the filenameyou can call open(to open new file in 'wb"write binarymode remember from earlier in this that to save files you've downloaded using requestsyou need to loop over the return value of the iter _content(method the code in the for loop writes out chunks of the image data (at most , bytes eachto the file and then you close the file the image is now saved to your hard drive afterwardthe selector ' [rel="prev"]identifies the element with the rel attribute set to prevand you can use this element' href attribute to get the previous comic' urlwhich gets stored in url then the while loop begins the entire download process again for this comic the output of this program will look like thisdownloading page downloading image downloading page downloading image downloading page downloading image downloading page downloading image downloading page downloading image downloading page downloading image --snip-this project is good example of program that can automatically follow links in order to scrape large amounts of data from the web you can learn about beautiful soup' other features from its documentation at ideas for similar programs downloading pages and following links are the basis of many web crawling programs similar programs could also do the following back up an entire site by following all of its links copy all the messages off web forum duplicate the catalog of items for sale on an online store
2,774
the url you need to pass to requests get(howeversometimes this isn' so easy to find or perhaps the website you want your program to navigate requires you to log in first the selenium module will give your programs the power to perform such sophisticated tasks controlling the browser with the selenium module the selenium module lets python directly control the browser by programmatically clicking links and filling in login informationalmost as though there were human user interacting with the page using seleniumyou can interact with web pages in much more advanced way than with requests and bs but because it launches web browserit is bit slower and hard to run in the background ifsayyou just need to download some files from the web stillif you need to interact with web page in way thatsaydepends on the javascript code that updates the pageyou'll need to use selenium instead of requests that' because major ecommerce websites such as amazon almost certainly have software systems to recognize traffic that they suspect is script harvesting their info or signing up for multiple free accounts these sites may refuse to serve pages to you after whilebreaking any scripts you've made the selenium module is much more likely to function on these sites long-term than requests major "tellto websites that you're using script is the user-agent stringwhich identifies the web browser and is included in all http requests for examplethe user-agent string for the requests module is something like 'python-requests/you can visit site such as www whatsmyua infoto see your user-agent string using seleniumyou're much more likely to "pass for humanbecause not only is selenium' useragent is the same as regular browser (for instance'mozilla/ (windows nt win rv: gecko/ firefox/ ')but it has the same traffic patternsa selenium-controlled browser will download imagesadvertisementscookiesand privacy-invading trackers just like regular browser howeverselenium can still be detected by websitesand major ticketing and ecommerce websites often block browsers controlled by selenium to prevent web scraping of their pages starting selenium-controlled browser the following examples will show you how to control firefox' web browser if you don' already have firefoxyou can download it for free from getfirefox comyou can install selenium by running pip install --user selenium from command line terminal more information is available in appendix importing the modules for selenium is slightly tricky instead of import seleniumyou need to run from selenium import webdriver (the exact reason why the selenium module is set up this way is beyond the scope of this book web scraping
2,775
following into the interactive shellfrom selenium import webdriver browser webdriver firefox(type(browserbrowser get('you'll notice when webdriver firefox(is calledthe firefox web browser starts up calling type(on the value webdriver firefox(reveals it' of the webdriver data type and calling browser get('directs the browser to look something like figure - figure - after we call webdriver firefox(and get(in muthe firefox browser appears if you encounter the error message "'geckodriverexecutable needs to be in path "then you need to manually download the webdriver for firefox before you can use selenium to control it you can also control browsers other than firefox if you install the webdriver for them for firefoxgo to browser engine used in firefox for exampleon windows you'll want to download the geckodriver- -win zip linkand on macosyou'll want the geckodriver- -macos tar gz link newer versions will have slightly different links the downloaded zip file will contain geckodriver exe (on windowsor geckodriver (on macos and linuxfile that you can put on your system path appendix has information about the system pathor you can learn more at
2,776
downloads and download the zip file for your operating system this zip file will contain chromedriver exe (on windowsor chromedriver (on macos or linuxfile that you can put on your system path other major web browsers also have webdrivers availableand you can often find these by performing an internet search for "<browser namewebdriverif you still have problems opening up new browser under the control of seleniumit may be because the current version of the browser is incompatible with the selenium module one workaround is to install an older version of the web browser--ormore simplyan older version of the selenium module you can find the list of selenium version numbers at /project/selenium/#history unfortunatelythe compatibility between versions of selenium and browser sometimes breaksand you may need to search the web for possible solutions appendix has more information about running pip to install specific version of selenium (for exampleyou might run pip install --user - selenium=finding elements on the page webdriver objects have quite few methods for finding elements on page they are divided into the find_element_and find_elements_methods the find_element_methods return single webelement objectrepresenting the first element on the page that matches your query the find_elements_methods return list of webelement_objects for every matching element on the page table - shows several examples of find_element_and find_elements_methods being called on webdriver object that' stored in the variable browser table - selenium' webdriver methods for finding elements method name webelement object/list returned browser find_element_by_class_name(namebrowser find_elements_by_class_name(nameelements that use the css class name browser find_element_by_css_selector(selectorbrowser find_elements_by_css_selector(selectorelements that match the css selector browser find_element_by_id(idbrowser find_elements_by_id(idelements with matching id attribute value browser find_element_by_link_text(textbrowser find_elements_by_link_text(textelements that completely browser find_element_by_partial_link_text(textbrowser find_elements_by_partial_link_text(textelements that contain the browser find_element_by_name(namebrowser find_elements_by_name(nameelements with matching name attribute value browser find_element_by_tag_name(namebrowser find_elements_by_tag_name(nameelements with matching tag name (case-insensitivean element is matched by 'aand ' 'match the text provided text provided web scraping
2,777
method is looking forthe selenium module raises nosuchelement exception if you do not want this exception to crash your programadd try and except statements to your code once you have the webelement objectyou can find out more about it by reading the attributes or calling the methods in table - table - webelement attributes and methods attribute or method description tag_name the tag namesuch as 'afor an element get_attribute(namethe value for the element' name attribute text the text within the elementsuch as 'helloin hello clear(for text field or text area elementsclears the text typed into it is_displayed(returns true if the element is visibleotherwise returns false is_enabled(for input elementsreturns true if the element is enabledotherwise returns false is_selected(for checkbox or radio button elementsreturns true if the element is selectedotherwise returns false location dictionary with keys 'xand 'yfor the position of the element in the page for exampleopen new file editor tab and enter the following programfrom selenium import webdriver browser webdriver firefox(browser get('tryelem browser find_element_by_class_name(cover-thumb'print('found element with that class name!(elem tag_name)exceptprint('was not able to find an element with that name 'here we open firefox and direct it to url on this pagewe try to find elements with the class name 'bookcover'and if such an element is foundwe print its tag name using the tag_name attribute if no such element was foundwe print different message this program will output the followingfound element with that class namewe found an element with the class name 'bookcoverand the tag name 'img
2,778
webelement objects returned from the find_element_and find_elements_methods have click(method that simulates mouse click on that element this method can be used to follow linkmake selection on radio buttonclick submit buttonor trigger whatever else might happen when the element is clicked by the mouse for exampleenter the following into the interactive shellfrom selenium import webdriver browser webdriver firefox(browser get(linkelem browser find_element_by_link_text('read online for free'type(linkelemlinkelem click(follows the "read online for freelink this opens firefox to object for the element with the text read it onlineand then simulates clicking that element it' just like if you clicked the link yourselfthe browser then follows that link filling out and submitting forms sending keystrokes to text fields on web page is matter of finding the or element for that text field and then calling the send _keys()method for exampleenter the following into the interactive shellfrom selenium import webdriver browser webdriver firefox(browser get(userelem browser find_element_by_id('user_nameuserelem send_keys('your_real_username_here'passwordelem browser find_element_by_id('user_pass'passwordelem send_keys('your_real_password_here'passwordelem submit(as long as login page for metafilter hasn' changed the id of the username and password text fields since this book was publishedthe previous code will fill in those text fields with the provided text (you can always use the browser' inspector to verify the id calling the submit(method on any element will have the same result as clicking the submit button for the form that element is in (you could have just as easily called emailelem submit()and the code would have done the same thing warning avoid putting your passwords in source code whenever possible it' easy to accidentally leak your passwords to others when they are left unencrypted on your hard drive if possiblehave your program prompt users to enter their passwords from the keyboard using the pyinputplus inputpassword(function described in web scraping
2,779
the selenium module has module for keyboard keys that are impossible to type into string valuewhich function much like escape characters these values are stored in attributes in the selenium webdriver common keys module since that is such long module nameit' much easier to run from selenium webdriver common keys import keys at the top of your programif you dothen you can simply write keys anywhere you' normally have to write selenium webdriver common keys table - lists the commonly used keys variables table - commonly used variables in the selenium webdriver common keys module attributes meanings keys downkeys upkeys leftkeys right the keyboard arrow keys keys enterkeys return the enter and return keys keys homekeys endkeys page_downkeys page_up the homeendpagedownand pageup keys keys escapekeys back_spacekeys delete the escbackspaceand delete keys keys keys keys the to keys at the top of the keyboard keys tab the tab key for exampleif the cursor is not currently in text fieldpressing the home and end keys will scroll the browser to the top and bottom of the pagerespectively enter the following into the interactive shelland notice how the send_keys(calls scroll the pagefrom selenium import webdriver from selenium webdriver common keys import keys browser webdriver firefox(browser get(htmlelem browser find_element_by_tag_name('html'htmlelem send_keys(keys endscrolls to bottom htmlelem send_keys(keys homescrolls to top the tag is the base tag in html filesthe full content of the html file is enclosed within the and tags calling browser find_element_by_tag_name('html'is good place to send keys to the general web page this would be useful iffor examplenew content is loaded once you've scrolled to the bottom of the page
2,780
the selenium module can simulate clicks on various browser buttons as well through the following methodsclicks the back button clicks the forward button browser refresh(clicks the refresh/reload button browser quit(clicks the close window button browser back(browser forward(more information on selenium selenium can do much more beyond the functions described here it can modify your browser' cookiestake screenshots of web pagesand run custom javascript to learn more about these featuresyou can visit the selenium documentation at summary most boring tasks aren' limited to the files on your computer being able to programmatically download web pages will extend your programs to the internet the requests module makes downloading straightforwardand with some basic knowledge of html concepts and selectorsyou can utilize the beautifulsoup module to parse the pages you download but to fully automate any web-based tasksyou need direct control of your web browser through the selenium module the selenium module will allow you to log in to websites and fill out forms automatically since web browser is the most common way to send and receive information over the internetthis is great ability to have in your programmer toolkit practice questions briefly describe the differences between the webbrowserrequestsbs and selenium modules what type of object is returned by requests get()how can you access the downloaded content as string valuewhat requests method checks that the download workedhow can you get the http status code of requests responsehow do you save requests response to filewhat is the keyboard shortcut for opening browser' developer toolshow can you view (in the developer toolsthe html of specific element on web pagewhat is the css selector string that would find the element with an id attribute of mainweb scraping
2,781
what is the css selector string that would find the elements with css class of highlight what is the css selector string that would find all the elements inside another element what is the css selector string that would find the element with value attribute set to favorite say you have beautiful soup tag object stored in the variable spam for the element helloworldhow could you get string 'helloworld!from the tag object how would you store all the attributes of beautiful soup tag object in variable named linkelem running import selenium doesn' work how do you properly import the selenium module what' the difference between the find_element_and find_elements_methods what methods do selenium' webelement objects have for simulating mouse clicks and keyboard keys you could call send_keys(keys enteron the submit button' webelement objectbut what is an easier way to submit form with selenium how can you simulate clicking browser' forwardbackand refresh buttons with seleniumpractice projects for practicewrite programs to do the following tasks command line emailer write program that takes an email address and string of text on the command line and thenusing seleniumlogs in to your email account and sends an email of the string to the provided address (you might want to set up separate email account for this program this would be nice way to add notification feature to your programs you could also write similar program to send messages from facebook or twitter account image site downloader write program that goes to photo-sharing site like flickr or imgursearches for category of photosand then downloads all the resulting images you could write program that works with any photo site that has search feature
2,782
is simple game where you combine tiles by sliding them updownleftor right with the arrow keys you can actually get fairly high score by repeatedly sliding in an uprightdownand left pattern over and over again write program that will open the game at github io/ and keep sending uprightdownand left keystrokes to automatically play the game link verification write program thatgiven the url of web pagewill attempt to download every linked page on the page the program should flag any pages that have "not foundstatus code and print them out as broken links web scraping
2,783
working with xcel spre adshee ts although we don' often think of spreadsheets as programming toolsalmost everyone uses them to organize information into two-dimensional data structuresperform calculations with formulasand produce output as charts in the next two we'll integrate python into two popular spreadsheet applicationsmicrosoft excel and google sheets excel is popular and powerful spreadsheet application for windows the openpyxl module allows your python programs to read and modify excel spreadsheet files for exampleyou might have the boring task of copying certain data from one spreadsheet and pasting it into another one or you might have to go through thousands of rows and pick out just handful of them to make small edits based on some criteria or you might have to look through hundreds of spreadsheets of department budgetssearching for any that are in the red these are exactly the sort of boringmindless spreadsheet tasks that python can do for you
2,784
are free alternatives that run on windowsmacosand linux both libreoffice calc and openoffice calc work with excel' xlsx file format for spreadsheetswhich means the openpyxl module can work on spreadsheets from these applications as well you can download the software from if you already have excel installed on your computeryou may find these programs easier to use the screenshots in this howeverare all from excel on windows excel documents firstlet' go over some basic definitionsan excel spreadsheet document is called workbook single workbook is saved in file with the xlsx extension each workbook can contain multiple sheets (also called worksheetsthe sheet the user is currently viewing (or last viewed before closing excelis called the active sheet each sheet has columns (addressed by letters starting at aand rows (addressed by numbers starting at box at particular column and row is called cell each cell can contain number or text value the grid of cells with data makes up sheet installing the openpyxl module python does not come with openpyxlso you'll have to install it follow the instructions for installing third-party modules in appendix athe name of the module is openpyxl this book uses version of openpyxl it' important that you install this version by running pip install --user - openpyxl=because newer versions of openpyxl are incompatible with the information in this book to test whether it is installed correctlyenter the following into the interactive shellimport openpyxl if the module was correctly installedthis should produce no error messages remember to import the openpyxl module before running the interactive shell examples in this or you'll get nameerrorname 'openpyxlis not defined error you can find the full documentation for openpyxl at readthedocs orgreading excel documents the examples in this will use spreadsheet named example xlsx stored in the root folder you can either create the spreadsheet yourself or download it from
2,785
automatically provides for new workbooks (the number of default sheets created may vary between operating systems and spreadsheet programs figure - the tabs for workbook' sheets are in the lower-left corner of excel sheet in the example file should look like table - (if you didn' download example xlsx from the websiteyou should enter this data into the sheet yourself table - the example xlsx spreadsheet : : pm apples : : am cherries : : pm pears : : am oranges : : am apples : : pm bananas : : am strawberries now that we have our example spreadsheetlet' see how we can manipulate it with the openpyxl module opening excel documents with openpyxl once you've imported the openpyxl moduleyou'll be able to use the openpyxl load_workbook(function enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'type(wbthe openpyxl load_workbook(function takes in the filename and returns value of the workbook data type this workbook object represents the excel filea bit like how file object represents an opened text file remember that example xlsx needs to be in the current working directory in order for you to work with it you can find out what the current working directory is by importing os and using os getcwd()and you can change the current working directory using os chdir(working with excel spreadsheets
2,786
you can get list of all the sheet names in the workbook by accessing the sheetnames attribute enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'wb sheetnames the workbook' sheetsnames ['sheet ''sheet ''sheet 'sheet wb['sheet 'get sheet from the workbook sheet type(sheetsheet title get the sheet' title as string 'sheet anothersheet wb active get the active sheet anothersheet each sheet is represented by worksheet objectwhich you can obtain by using the square brackets with the sheet name string like dictionary key finallyyou can use the active attribute of workbook object to get the workbook' active sheet the active sheet is the sheet that' on top when the workbook is opened in excel once you have the worksheet objectyou can get its name from the title attribute getting cells from the sheets once you have worksheet objectyou can access cell object by its name enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'sheet wb['sheet 'get sheet from the workbook sheet[' 'get cell from the sheet sheet[' 'value get the value from the cell datetime datetime( sheet[' 'get another cell from the sheet value 'applesget the rowcolumnand value from the cell 'row %scolumn % is % ( rowc columnc value'row column is apples'cell % is % ( coordinatec value'cell is applessheet[' 'value the cell object has value attribute that containsunsurprisinglythe value stored in that cell cell objects also have rowcolumnand coordinate attributes that provide location information for the cell
2,787
the string 'applesthe row attribute gives us the integer the column attribute gives us ' 'and the coordinate attribute gives us ' openpyxl will automatically interpret the dates in column and return them as datetime values rather than strings the datetime data type is explained further in specifying column by letter can be tricky to programespecially because after column zthe columns start by using two lettersaaabacand so on as an alternativeyou can also get cell using the sheet' cell(method and passing integers for its row and column keyword arguments the first row or column integer is not continue the interactive shell example by entering the followingsheet cell(row= column= sheet cell(row= column= value 'applesfor in range( )go through every other rowprint(isheet cell(row=icolumn= value apples pears apples strawberries as you can seeusing the sheet' cell(method and passing it row= and column= gets you cell object for cell just like specifying sheet[' 'did thenusing the cell(method and its keyword argumentsyou can write for loop to print the values of series of cells say you want to go down column and print the value in every cell with an odd row number by passing for the range(function' "stepparameteryou can get cells from every second row (in this caseall the odd-numbered rowsthe for loop' variable is passed for the row keyword argument to the cell(methodwhile is always passed for the column keyword argument note that the integer not the string ' 'is passed you can determine the size of the sheet with the worksheet object' max_row and max_column attributes enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'sheet wb['sheet 'sheet max_row get the highest row number sheet max_column get the highest column number note that the max_column attribute is an integer rather than the letter that appears in excel working with excel spreadsheets
2,788
to convert from letters to numberscall the openpyxl utils column_index_from _string(function to convert from numbers to letterscall the openpyxl utils get_column_letter(function enter the following into the interactive shellimport openpyxl from openpyxl utils import get_column_lettercolumn_index_from_string get_column_letter( translate column to letter 'aget_column_letter( 'bget_column_letter( 'aaget_column_letter( 'ahpwb openpyxl load_workbook('example xlsx'sheet wb['sheet 'get_column_letter(sheet max_column'ccolumn_index_from_string(' 'get ' number column_index_from_string('aa' after you import these two functions from the openpyxl utils moduleyou can call get_column_letter(and pass it an integer like to figure out what the letter name of the th column is the function column_index_string(does the reverseyou pass it the letter name of columnand it tells you what number that column is you don' need to have workbook loaded to use these functions if you wantyou can load workbookget worksheet objectand use worksheet attribute like max_column to get an integer thenyou can pass that integer to get_column_letter(getting rows and columns from the sheets you can slice worksheet objects to get all the cell objects in rowcolumnor rectangular area of the spreadsheet then you can loop over all the cells in the slice enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'sheet wb['sheet 'tuple(sheet[' ':' ']get all cells from to (()(<cell 'sheet >)()for rowofcellobjects in sheet[' ':' ']for cellobj in rowofcellobjectsprint(cellobj coordinatecellobj valueprint('--end of row ---' : :
2,789
--end of row -- : : cherries --end of row -- : : pears --end of row --herewe specify that we want the cell objects in the rectangular area from to and we get generator object containing the cell objects in that area to help us visualize this generator objectwe can use tuple(on it to display its cell objects in tuple this tuple contains three tuplesone for each rowfrom the top of the desired area to the bottom each of these three inner tuples contains the cell objects in one row of our desired areafrom the leftmost cell to the right so overallour slice of the sheet contains all the cell objects in the area from to starting from the top-left cell and ending with the bottom-right cell to print the values of each cell in the areawe use two for loops the outer for loop goes over each row in the slice thenfor each rowthe nested for loop goes through each cell in that row to access the values of cells in particular row or columnyou can also use worksheet object' rows and columns attribute these attributes must be converted to lists with the list(function before you can use the square brackets and an index with them enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('example xlsx'sheet wb active list(sheet columns)[ get second column' cells (<cell 'sheet >for cellobj in list(sheet columns)[ ]print(cellobj valueapples cherries pears oranges apples bananas strawberries using the rows attribute on worksheet object will give you tuple of tuples each of these inner tuples represents rowand contains the cell objects in that row the columns attribute also gives you tuple of tupleswith each of the inner tuples containing the cell objects in particular working with excel spreadsheets
2,790
us tuple of tuples (each containing cell objects)and columns gives us tuple of tuples (each containing cell objectsto access one particular tupleyou can refer to it by its index in the larger tuple for exampleto get the tuple that represents column byou use list(sheet columns)[ to get the tuple containing the cell objects in column ayou' use list(sheet columns)[ once you have tuple representing one row or columnyou can loop through its cell objects and print their values workbookssheetscells as quick reviewhere' rundown of all the functionsmethodsand data types involved in reading cell out of spreadsheet file import the openpyxl module call the openpyxl load_workbook(function get workbook object use the active or sheetnames attributes get worksheet object use indexing or the cell(sheet method with row and column keyword arguments get cell object read the cell object' value attribute projectreading data from spreadsheet say you have spreadsheet of data from the us census and you have the boring task of going through its thousands of rows to count both the total population and the number of census tracts for each county ( census tract is simply geographic area defined for the purposes of the census each row represents single census tract we'll name the spreadsheet file censuspopdata xlsxand you can download it from /automatestuff its contents look like figure - figure - the censuspopdata xlsx spreadsheet
2,791
you' still have to select the cells for each of the , -plus counties even if it takes just few seconds to calculate county' population by handthis would take hours to do for the whole spreadsheet in this projectyou'll write script that can read from the census spreadsheet file and calculate statistics for each county in matter of seconds this is what your program does reads the data from the excel spreadsheet counts the number of census tracts in each county counts the total population of each county prints the results this means your code will need to do the following open and read the cells of an excel document with the openpyxl module calculate all the tract and population data and store it in data structure write the data structure to text file with the py extension using the pprint module step read the spreadsheet data there is just one sheet in the censuspopdata xlsx spreadsheetnamed 'population by census tract'and each row holds the data for single census tract the columns are the tract number ( )the state abbreviation ( )the county name ( )and the population of the tract (dopen new file editor tab and enter the following code save the file as readcensusexcel py #python readcensusexcel py tabulates population and number of census tracts for each county import openpyxlpprint print('opening workbook 'wb openpyxl load_workbook('censuspopdata xlsx'sheet wb['population by census tract'countydata {todofill in countydata with each county' population and tracts print('reading rows 'for row in range( sheet max_row )each row in the spreadsheet has data for one census tract state sheet['bstr(row)value county sheet['cstr(row)value pop sheet['dstr(row)value todoopen new text file and write the contents of countydata to it working with excel spreadsheets
2,792
you'll use to print the final county data then it opens the censuspopdata xlsx file gets the sheet with the census data and begins iterating over its rows note that you've also created variable named countydatawhich will contain the populations and number of tracts you calculate for each county before you can store anything in itthoughyou should determine exactly how you'll structure the data inside it step populate the data structure the data structure stored in countydata will be dictionary with state abbreviations as its keys each state abbreviation will map to another dictionarywhose keys are strings of the county names in that state each county name will in turn map to dictionary with just two keys'tractsand 'popthese keys map to the number of census tracts and population for the county for examplethe dictionary will look similar to this{'ak'{'aleutians east'{'pop' 'tracts' }'aleutians west'{'pop' 'tracts' }'anchorage'{'pop' 'tracts' }'bethel'{'pop' 'tracts' }'bristol bay'{'pop' 'tracts' }--snip-if the previous dictionary were stored in countydatathe following expressions would evaluate like thiscountydata['ak']['anchorage']['pop' countydata['ak']['anchorage']['tracts' more generallythe countydata dictionary' keys will look like thiscountydata[state abbrev][county]['tracts'countydata[state abbrev][county]['pop'now that you know how countydata will be structuredyou can write the code that will fill it with the county data add the following code to the bottom of your program#python readcensusexcel py tabulates population and number of census tracts for each county --snip-
2,793
each row in the spreadsheet has data for one census tract state sheet['bstr(row)value county sheet['cstr(row)value pop sheet['dstr(row)value make sure the key for this state exists countydata setdefault(state{}make sure the key for this county in this state exists countydata[statesetdefault(county{'tracts' 'pop' }each row represents one census tractso increment by one countydata[state][county]['tracts'+ increase the county pop by the pop in this census tract countydata[state][county]['pop'+int(poptodoopen new text file and write the contents of countydata to it the last two lines of code perform the actual calculation workincrementing the value for tracts and increasing the value for pop for the current county on each iteration of the for loop the other code is there because you cannot add county dictionary as the value for state abbreviation key until the key itself exists in countydata (that iscountydata['ak']['anchorage']['tracts'+ will cause an error if the 'akkey doesn' exist yet to make sure the state abbreviation key exists in your data structureyou need to call the setdefault(method to set value if one does not already exist for state just as the countydata dictionary needs dictionary as the value for each state abbreviation keyeach of those dictionaries will need its own dictionary as the value for each county key and each of those dictionaries in turn will need keys 'tractsand 'popthat start with the integer value (if you ever lose track of the dictionary structurelook back at the example dictionary at the start of this section since setdefault(will do nothing if the key already existsyou can call it on every iteration of the for loop without problem step write the results to file after the for loop has finishedthe countydata dictionary will contain all of the population and tract information keyed by county and state at this pointyou could program more code to write this to text file or another excel spreadsheet for nowlet' just use the pprint pformat(function to write the countydata dictionary value as massive string to file named census py add the following code to the bottom of your program (making sure to keep it unindented so that it stays outside the for loop)#python readcensusexcel py tabulates population and number of census tracts for each county working with excel spreadsheets
2,794
--snip-open new text file and write the contents of countydata to it print('writing results 'resultfile open('census py'' 'resultfile write('alldata pprint pformat(countydata)resultfile close(print('done 'the pprint pformat(function produces string that itself is formatted as valid python code by outputting it to text file named census pyyou've generated python program from your python programthis may seem complicatedbut the advantage is that you can now import census py just like any other python module in the interactive shellchange the current working directory to the folder with your newly created census py file and then import itimport os import census census alldata['ak']['anchorage'{'pop' 'tracts' anchoragepop census alldata['ak']['anchorage']['pop'print('the population of anchorage was str(anchoragepop)the population of anchorage was the readcensusexcel py program was throwaway codeonce you have its results saved to census pyyou won' need to run the program again whenever you need the county datayou can just run import census calculating this data by hand would have taken hoursthis program did it in few seconds using openpyxlyou will have no trouble extracting information that is saved to an excel spreadsheet and performing calculations on it you can download the complete program from com/automatestuff ideas for similar programs many businesses and offices use excel to store various types of dataand it' not uncommon for spreadsheets to become large and unwieldy any program that parses an excel spreadsheet has similar structureit loads the spreadsheet filepreps some variables or data structuresand then loops through each of the rows in the spreadsheet such program could do the following compare data across multiple rows in spreadsheet open multiple excel files and compare data between spreadsheets
2,795
check whether spreadsheet has blank rows or invalid data in any cells and alert the user if it does read data from spreadsheet and use it as the input for your python programs writing excel documents openpyxl also provides ways of writing datameaning that your programs can create and edit spreadsheet files with pythonit' simple to create spreadsheets with thousands of rows of data creating and saving excel documents call the openpyxl workbook(function to create newblank workbook object enter the following into the interactive shellimport openpyxl wb openpyxl workbook(create blank workbook wb sheetnames it starts with one sheet ['sheet'sheet wb active sheet title 'sheetsheet title 'spam bacon eggs sheetchange title wb sheetnames ['spam bacon eggs sheet'the workbook will start off with single sheet named sheet you can change the name of the sheet by storing new string in its title attribute any time you modify the workbook object or its sheets and cellsthe spreadsheet file will not be saved until you call the save(workbook method enter the following into the interactive shell (with example xlsx in the current working directory)import openpyxl wb openpyxl load_workbook('example xlsx'sheet wb active sheet title 'spam spam spamwb save('example_copy xlsx'save the workbook herewe change the name of our sheet to save our changeswe pass filename as string to the save(method passing different filename than the originalsuch as 'example_copy xlsx'saves the changes to copy of the spreadsheet whenever you edit spreadsheet you've loaded from fileyou should always save the newedited spreadsheet to different filename than the original that wayyou'll still have the original spreadsheet file to work with in case bug in your code caused the newsaved file to have incorrect or corrupt data working with excel spreadsheets
2,796
sheets can be added to and removed from workbook with the create_sheet(method and del operator enter the following into the interactive shellimport openpyxl wb openpyxl workbook(wb sheetnames ['sheet'wb create_sheet(add new sheet wb sheetnames ['sheet''sheet 'create new sheet at index wb create_sheet(index= title='first sheet'wb sheetnames ['first sheet''sheet''sheet 'wb create_sheet(index= title='middle sheet'wb sheetnames ['first sheet''sheet''middle sheet''sheet 'the create_sheet(method returns new worksheet object named sheetxwhich by default is set to be the last sheet in the workbook optionallythe index and name of the new sheet can be specified with the index and title keyword arguments continue the previous example by entering the followingwb sheetnames ['first sheet''sheet''middle sheet''sheet 'del wb['middle sheet'del wb['sheet 'wb sheetnames ['first sheet''sheet'you can use the del operator to delete sheet from workbookjust like you can use it to delete key-value pair from dictionary remember to call the save(method to save the changes after adding sheets to or removing sheets from the workbook writing values to cells writing values to cells is much like writing values to keys in dictionary enter this into the interactive shellimport openpyxl wb openpyxl workbook(sheet wb['sheet'sheet[' ''helloworld!edit the cell' value sheet[' 'value 'helloworld!
2,797
dictionary key on the worksheet object to specify which cell to write to projectupdating spreadsheet in this projectyou'll write program to update cells in spreadsheet of produce sales your program will look through the spreadsheetfind specific kinds of produceand update their prices download this spreadsheet from figure - spreadsheet of produce sales each row represents an individual sale the columns are the type of produce sold ( )the cost per pound of that produce ( )the number of pounds sold ( )and the total revenue from the sale (dthe total column is set to the excel formula =round( * )which multiplies the cost per pound by the number of pounds sold and rounds the result to the nearest cent with this formulathe cells in the total column will automatically update themselves if there is change in column or now imagine that the prices of garlicceleryand lemons were entered incorrectlyleaving you with the boring task of going through thousands of rows in this spreadsheet to update the cost per pound for any garlicceleryand lemon rows you can' do simple find-and-replace for the pricebecause there might be other items with the same price that you don' want to mistakenly "correct for thousands of rowsthis would take hours to do by hand but you can write program that can accomplish this in seconds your program does the following loops over all the rows if the row is for garlicceleryor lemonschanges the price working with excel spreadsheets
2,798
open the spreadsheet file for each rowcheck whether the value in column is celerygarlicor lemon if it isupdate the price in column save the spreadsheet to new file (so that you don' lose the old spreadsheetjust in casestep set up data structure with the update information the prices that you need to update are as followscelery garlic lemon you could write code like thisif producename ='celery'cellobj if producename ='garlic'cellobj if producename ='lemon'cellobj having the produce and updated price data hardcoded like this is bit inelegant if you needed to update the spreadsheet again with different prices or different produceyou would have to change lot of the code every time you change codeyou risk introducing bugs more flexible solution is to store the corrected price information in dictionary and write your code to use this data structure in new file editor tabenter the following code#python updateproduce py corrects costs in produce sales spreadsheet import openpyxl wb openpyxl load_workbook('producesales xlsx'sheet wb['sheet'the produce types and their updated prices price_updates {'garlic' 'celery' 'lemon' todoloop through the rows and update the prices save this as updateproduce py if you need to update the spreadsheet againyou'll need to update only the price_updates dictionarynot any other code
2,799
the next part of the program will loop through all the rows in the spreadsheet add the following code to the bottom of updateproduce py#python updateproduce py corrects costs in produce sales spreadsheet --snip-loop through the rows and update the prices for rownum in range( sheet max_row)skip the first row producename sheet cell(row=rownumcolumn= value if producename in price_updatessheet cell(row=rownumcolumn= value price_updates[producenamewb save('updatedproducesales xlsx'we loop through the rows starting at row since row is just the header the cell in column (that iscolumn awill be stored in the variable producename if producename exists as key in the price_updates dictionary then you know this is row that must have its price corrected the correct price will be in price_updates[producenamenotice how clean using price_updates makes the code only one if statementrather than code like if producename ='garlic'is necessary for every type of produce to update and since the code uses the price_updates dictionary instead of hardcoding the produce names and updated costs into the for loopyou modify only the price_updates dictionary and not the code if the produce sales spreadsheet needs additional changes after going through the entire spreadsheet and making changesthe code saves the workbook object to updatedproducesales xlsx it doesn' overwrite the old spreadsheet just in case there' bug in your program and the updated spreadsheet is wrong after checking that the updated spreadsheet looks rightyou can delete the old spreadsheet you can download the complete source code for this program from ideas for similar programs since many office workers use excel spreadsheets all the timea program that can automatically edit and write excel files could be really useful such program could do the followingread data from one spreadsheet and write it to parts of other spreadsheets read data from websitestext filesor the clipboard and write it to spreadsheet automatically "clean updata in spreadsheets for exampleit could use regular expressions to read multiple formats of phone numbers and edit them to singlestandard format working with excel spreadsheets