id
int64 0
25.6k
| text
stringlengths 0
4.59k
|
---|---|
2,800 | styling certain cellsrowsor columns can help you emphasize important areas in your spreadsheet in the produce spreadsheetfor exampleyour program could apply bold text to the potatogarlicand parsnip rows or perhaps you want to italicize every row with cost per pound greater than $ styling parts of large spreadsheet by hand would be tediousbut your programs can do it instantly to customize font styles in cellsimportantimport the font(function from the openpyxl styles module from openpyxl styles import font this allows you to type font(instead of openpyxl styles font((see "importing moduleson page to review this style of import statement here' an example that creates new workbook and sets cell to have -pointitalicized font enter the following into the interactive shellimport openpyxl from openpyxl styles import font wb openpyxl workbook(sheet wb['sheet'italic font font(size= italic=truecreate font sheet[' 'font italic font apply the font to sheet[' ''helloworld!wb save('styles xlsx'in this examplefont(size= italic=truereturns font objectwhich is stored in italic font the keyword arguments to font()size and italicconfigure the font object' styling information and when sheet[' 'font is assigned the italic font object all that font styling information gets applied to cell font objects to set font attributesyou pass keyword arguments to font(table - shows the possible keyword arguments for the font(function table - keyword arguments for font objects keyword argument data type description name string the font namesuch as 'calibrior 'times new romansize integer the point size bold boolean truefor bold font italic boolean truefor italic font |
2,801 | variable you then assign that variable to cell object' font attribute for examplethis code creates various font stylesimport openpyxl from openpyxl styles import font wb openpyxl workbook(sheet wb['sheet'fontobj font(name='times new roman'bold=truesheet[' 'font fontobj sheet[' ''bold times new romanfontobj font(size= italic=truesheet[' 'font fontobj sheet[' '' pt italicwb save('styles xlsx'herewe store font object in fontobj and then set the cell object' font attribute to fontobj we repeat the process with another font object to set the font of second cell after you run this codethe styles of the and cells in the spreadsheet will be set to custom font stylesas shown in figure - figure - spreadsheet with custom font styles for cell we set the font name to 'times new romanand set bold to trueso our text appears in bold times new roman we didn' specify sizeso the openpyxl default is used in cell our text is italicwith size of we didn' specify font nameso the openpyxl defaultcalibriis used formulas excel formulaswhich begin with an equal signcan configure cells to contain values calculated from other cells in this sectionyou'll use the openpyxl module to programmatically add formulas to cellsjust like any normal value for examplesheet[' ''=sum( : )working with excel spreadsheets |
2,802 | to formula that calculates the sum of values in cells to you can see this in action in figure - figure - cell contains the formula =sum( : )which adds the cells to an excel formula is set just like any other text value in cell enter the following into the interactive shellimport openpyxl wb openpyxl workbook(sheet wb active sheet[' ' sheet[' ' sheet[' ''=sum( : )set the formula wb save('writeformula xlsx'the cells in and are set to and respectively the value in cell is set to formula that sums the values in and when the spreadsheet is opened in excela will display its value as excel formulas offer level of programmability for spreadsheets but can quickly become unmanageable for complicated tasks for exampleeven if you're deeply familiar with excel formulasit' headache to try to decipher what =iferror(trim(if(len(vlookup( sheet !$ $ :$ $ false))> ,substitute(vlookup( sheet !$ $ :$ $ false)"""),""))""actually does python code is much more readable adjusting rows and columns in exceladjusting the sizes of rows and columns is as easy as clicking and dragging the edges of row or column header but if you need to set row |
2,803 | large number of spreadsheet filesit will be much quicker to write python program to do it rows and columns can also be hidden entirely from view or they can be "frozenin place so that they are always visible on the screen and appear on every page when the spreadsheet is printed (which is handy for headerssetting row height and column width worksheet objects have row_dimensions and column_dimensions attributes that control row heights and column widths enter this into the interactive shellimport openpyxl wb openpyxl workbook(sheet wb active sheet[' ''tall rowsheet[' ''wide columnset the height and widthsheet row_dimensions[ height sheet column_dimensions[' 'width wb save('dimensions xlsx' sheet' row_dimensions and column_dimensions are dictionary-like valuesrow_dimensions contains rowdimension objects and column_dimensions contains columndimension objects in row_dimensionsyou can access one of the objects using the number of the row (in this case or in column_dimensionsyou can access one of the objects using the letter of the column (in this casea or bthe dimensions xlsx spreadsheet looks like figure - figure - row and column set to larger heights and widths once you have the rowdimension objectyou can set its height once you have the columndimension objectyou can set its width the row height can be set to an integer or float value between and this value represents the height measured in pointswhere one point equals / of an inch the default row height is the column width can be set to an integer or float value between and this value represents the number of characters at the default font size ( pointthat can be displayed in the cell the default column width is characters columns with widths of or rows with heights of are hidden from the user working with excel spreadsheets |
2,804 | rectangular area of cells can be merged into single cell with the merge_cells(sheet method enter the following into the interactive shellimport openpyxl wb openpyxl workbook(sheet wb active sheet merge_cells(' : 'merge all these cells sheet[' ''twelve cells merged together sheet merge_cells(' : 'merge these two cells sheet[' ''two merged cells wb save('merged xlsx'the argument to merge_cells(is single string of the top-left and bottomright cells of the rectangular area to be merged' : merges cells into single cell to set the value of these merged cellssimply set the value of the top-left cell of the merged group when you run this codemerged xlsx will look like figure - figure - merged cells in spreadsheet to unmerge cellscall the unmerge_cells(sheet method enter this into the interactive shellimport openpyxl wb openpyxl load_workbook('merged xlsx'sheet wb active sheet unmerge_cells(' : 'split these cells up sheet unmerge_cells(' : 'wb save('merged xlsx'if you save your changes and then take look at the spreadsheetyou'll see that the merged cells have gone back to being individual cells freezing panes for spreadsheets too large to be displayed all at onceit' helpful to "freezea few of the top rows or leftmost columns onscreen frozen column or row headersfor exampleare always visible to the user even as |
2,805 | openpyxleach worksheet object has freeze_panes attribute that can be set to cell object or string of cell' coordinates note that all rows above and all columns to the left of this cell will be frozenbut the row and column of the cell itself will not be frozen to unfreeze all panesset freeze_panes to none or ' table - shows which rows and columns will be frozen for some example settings of freeze_panes table - frozen pane examples freeze_panes setting rows and columns frozen sheet freeze_panes ' row sheet freeze_panes ' column sheet freeze_panes ' columns and sheet freeze_panes ' row and columns and sheet freeze_panes ' or sheet freeze_panes none no frozen panes make sure you have the produce sales spreadsheet from com/automatestuff then enter the following into the interactive shellimport openpyxl wb openpyxl load_workbook('producesales xlsx'sheet wb active sheet freeze_panes ' freeze the rows above wb save('freezeexample xlsx'if you set the freeze_panes attribute to ' 'row will always be viewableno matter where the user scrolls in the spreadsheet you can see this in figure - figure - with freeze_panes set to ' 'row is always visibleeven as the user scrolls down working with excel spreadsheets |
2,806 | openpyxl supports creating barlinescatterand pie charts using the data in sheet' cells to make chartyou need to do the following create reference object from rectangular selection of cells create series object by passing in the reference object create chart object append the series object to the chart object add the chart object to the worksheet objectoptionally specifying which cell should be the top-left corner of the chart the reference object requires some explaining you create reference objects by calling the openpyxl chart reference(function and passing three arguments the worksheet object containing your chart data tuple of two integersrepresenting the top-left cell of the rectangular selection of cells containing your chart datathe first integer in the tuple is the rowand the second is the column note that is the first rownot tuple of two integersrepresenting the bottom-right cell of the rectangular selection of cells containing your chart datathe first integer in the tuple is the rowand the second is the column figure - shows some sample coordinate arguments figure - from left to right( )( )( )( )( )( enter this interactive shell example to create bar chart and add it to the spreadsheetimport openpyxl wb openpyxl workbook(sheet wb active for in range( )create some data in column sheet['astr( ) refobj openpyxl chart reference(sheetmin_col= min_row= max_col= max_row= |
2,807 | chartobj openpyxl chart barchart(chartobj title 'my chartchartobj append(seriesobjsheet add_chart(chartobj' 'wb save('samplechart xlsx'this produces spreadsheet that looks like figure - the top-left corner is in figure - spreadsheet with chart added we've created bar chart by calling openpyxl chart barchart(you can also create line chartsscatter chartsand pie charts by calling openpyxl charts linechart()openpyxl chart scatterchart()and openpyxl chart piechart(summary often the hard part of processing information isn' the processing itself but simply getting the data in the right format for your program but once you have your spreadsheet loaded into pythonyou can extract and manipulate its data much faster than you could by hand you can also generate spreadsheets as output from your programs so if colleagues need your text file or pdf of thousands of sales contacts transferred to spreadsheet fileyou won' have to tediously copy and paste it all into excel equipped with the openpyxl module and some programming knowledgeyou'll find processing even the biggest spreadsheets piece of cake in the next we'll take look at using python to interact with another spreadsheet programthe popular online google sheets application working with excel spreadsheets |
2,808 | for the following questionsimagine you have workbook object in the variable wba worksheet object in sheeta cell object in cella comment object in command an image object in img what does the openpyxl load_workbook(function returnwhat does the wb sheetnames workbook attribute containhow would you retrieve the worksheet object for sheet named 'sheet 'how would you retrieve the worksheet object for the workbook' active sheet how would you retrieve the value in the cell how would you set the value in the cell to "hello" how would you retrieve the cell' row and column as integers what do the sheet max_column and sheet max_row sheet attributes holdand what is the data type of these attributes if you needed to get the integer index for column ' 'what function would you need to call if you needed to get the string name for column what function would you need to call how can you retrieve tuple of all the cell objects from to how would you save the workbook to the filename example xlsx how do you set formula in cell if you want to retrieve the result of cell' formula instead of the cell' formula itselfwhat must you do first how would you set the height of row to how would you hide column what is freeze pane what five functions and methods do you have to call to create bar chartpractice projects for practicewrite programs that perform the following tasks multiplication table maker create program multiplicationtable py that takes number from the command line and creates an nxn multiplication table in an excel spreadsheet for examplewhen the program is run like thispy multiplicationtable py it should create spreadsheet that looks like figure - |
2,809 | row and column should be used for labels and should be in bold blank row inserter create program blankrowinserter py that takes two integers and filename string as command line arguments let' call the first integer and the second integer starting at row nthe program should insert blank rows into the spreadsheet for examplewhen the program is run like thispython blankrowinserter py myproduce xlsx the "beforeand "afterspreadsheets should look like figure - figure - before (leftand after (rightthe two blank rows are inserted at row you can write this program by reading in the contents of the spreadsheet thenwhen writing out the new spreadsheetuse for loop to copy the first lines for the remaining linesadd to the row number in the output spreadsheet spreadsheet cell inverter write program to invert the row and column of the cells in the spreadsheet for examplethe value at row column will be at row column (and vice versathis should be done for all cells in the spreadsheet for examplethe "beforeand "afterspreadsheets would look something like figure - working with excel spreadsheets |
2,810 | you can write this program by using nested for loops to read the spreadsheet' data into list of lists data structure this data structure could have sheetdata[ ][yfor the cell at column and row thenwhen writing out the new spreadsheetuse sheetdata[ ][xfor the cell at column and row text files to spreadsheet write program to read in the contents of several text files (you can make the text files yourselfand insert those contents into spreadsheetwith one line of text per row the lines of the first text file will be in the cells of column athe lines of the second text file will be in the cells of column band so on use the readlines(file object method to return list of stringsone string per line in the file for the first fileoutput the first line to column row the second line should be written to column row and so on the next file that is read with readlines(will be written to column the next file to column and so on spreadsheet to text files write program that performs the tasks of the previous program in reverse orderthe program should open spreadsheet and write the cells of column into one text filethe cells of column into another text fileand so on |
2,811 | working with google shee ts google sheetsthe freeweb-based spreadsheet application available to anyone with google account or gmail addresshas become usefulfeature-rich competitor to excel google sheets has its own apibut this api can be confusing to learn and use this covers the ezsheets third-party moduledocumented at while not as full featured as the official google sheets apiezsheets makes common spreadsheet tasks easy to perform installing and setting up ezsheets you can install ezsheets by opening new terminal window and running pip install --user ezsheets as part of this installationezsheets will also install the google-api-python-clientgoogle-auth-httplib and |
2,812 | to google' servers and make api requests ezsheets handles the interaction with these modulesso you don' need to concern yourself with how they work obtaining credentials and token files before you can use ezsheetsyou need to enable the google sheets and google drive apis for your google account visit the following web pages and click the enable api buttons at the top of eachyou'll also need to obtain three fileswhich you should save in the same folder as your py python script that uses ezsheetsa credentials file named credentials-sheets json token for google sheets named token-sheets pickle token for google drive named token-drive pickle the credentials file will generate the token files the easiest way to obtain credentials file is to go to the google sheets python quickstart page at blue enable the google sheets api buttonas shown in figure - you'll need to log in to your google account to view this page figure - obtaining credentials json file clicking this button will bring up window with download client configuration link that lets you download credentials json file rename this file to credentials-sheets json and place it in the same folder as your python scripts |
2,813 | browser window for you to log in to your google account click allowas shown in figure - figure - allowing quickstart to access your google account the message about quickstart comes from the fact that you downloaded the credentials file from the google sheets python quickstart page note that this window will open twicefirst for google sheets access and second for google drive access ezsheets uses google drive access to uploaddownloadand delete spreadsheets after you log inthe browser window will prompt you to close itand the token-sheets pickle and token-drive pickle files will appear in the same folder as credentials-sheets json you only need to go through this process the first time you run import ezsheets if you encounter an error after clicking allow and the page seems to hangmake sure you have first enabled the google sheets and drive apis from the links at the start of this section it may take few minutes for google' servers to register this changeso you may have to wait before you can use ezsheets don' share the credential or token files with anyone--treat them like passwords working with google sheets |
2,814 | if you accidentally share the credential or token files with someonethey won' be able to change your google account passwordbut they will have access to your spreadsheets you can revoke these files by going to the google cloud platform developer' console page at account to view this page click the credentials link on the sidebar then click the trash can icon next to the credentials file you've accidentally sharedas shown in figure - create credentials button create credentials button create credentials button trashtrash trash can can iconicon can icon credentials credentials credentials sidebar link link sidebar sidebar link download download download iconicon icon figure - the credentials page in the google cloud platform developer' console to generate new credentials file from this pageclick the create credentials button and select oauth client idalso shown in figure - nextfor application typeselect other and give the file any name you like this new credentials file will then be listed on the pageand you can click on the download icon to download it the downloaded file will have longcomplicated filenameso you should rename it to the default filename that ezsheets attempts to loadcredentials-sheets json you can also generate new credential file by clicking the enable the google sheets api button mentioned in the previous section spreadsheet objects in google sheetsa spreadsheet can contain multiple sheets (also called worksheets)and each sheet contains columns and rows of values figure - shows spreadsheet titled "education datacontaining three sheets titled "students,"classes,and "resources the first column of each sheet is labeled aand the first row is labeled |
2,815 | while most of your work will involve modifying the sheet objectsyou can also modify spreadsheet objectsas you'll see in the next section creatinguploadingand listing spreadsheets you can make new spreadsheet object from an existing spreadsheeta blank spreadsheetor an uploaded spreadsheet to make spreadsheet object from an existing google sheets spreadsheetyou'll need the spreadsheet' id string the unique id for google sheets spreadsheet can be found in the urlafter the spreadsheets/dpart and before the /edit part for examplethe spreadsheet featured in figure - is located at the url google com/spreadsheets/ / -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu /edit#gid= /so its id is -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu note the specific spreadsheet ids used in this are for my google account' spreadsheets they won' work if you enter them into your interactive shell go to get the ids from the address bar pass your spreadsheet' id as string to the ezsheets spreadsheet(function to obtain spreadsheet object for its spreadsheetimport ezsheets ss ezsheets spreadsheet(' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu'ss spreadsheet(spreadsheetid=' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu'ss title 'education dataworking with google sheets |
2,816 | spreadsheet by passing the spreadsheet' full url to the function orif there is only one spreadsheet in your google account with that titleyou can pass the title of the spreadsheet as string to make newblank spreadsheetcall the ezsheets createspreadsheet(function and pass it string for the new spreadsheet' title for exampleenter the following into the interactive shellimport ezsheets ss ezsheets createspreadsheet('title of my new spreadsheet'ss title 'title of my new spreadsheetto upload an existing excelopenofficecsvor tsv spreadsheet to google sheetspass the filename of the spreadsheet to ezsheets upload(enter the following into the interactive shellreplacing my_spreadsheet xlsx with spreadsheet file of your ownimport ezsheets ss ezsheets upload('my_spreadsheet xlsx'ss title 'my_spreadsheetyou can list the spreadsheets in your google account by calling the listspreadsheets(function enter the following into the interactive shell after uploading spreadsheetezsheets listspreadsheets({' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu''education data'the listspreadsheets(function returns dictionary where the keys are spreadsheet ids and the values are the titles of each spreadsheet once you've obtained spreadsheet objectyou can use its attributes and methods to manipulate the online spreadsheet hosted on google sheets spreadsheet attributes while the actual data lives in spreadsheet' individual sheetsthe spreadsheet object has the following attributes for manipulating the spreadsheet itselftitlespreadsheetidurlsheettitlesand sheets enter the following into the interactive shellimport ezsheets ss ezsheets spreadsheet(' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu'ss title the title of the spreadsheet 'education datass title 'class datachange the title ss spreadsheetid the unique id (this is read-only attribute' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeuss url the original url (this is read-only attribute |
2,817 | ss sheettitles the titles of all the sheet objects ('students''classes''resources'ss sheets the sheet objects in this spreadsheetin order (<sheet sheetid= title='classes'rowcount= columncount= ><sheet sheetid= title='resources'rowcount= columncount= >ss[ the first sheet object in this spreadsheet ss['students'sheets can also be accessed by title del ss[ delete the first sheet object in this spreadsheet ss sheettitles the "studentssheet object has been deleted('classes''resources'if someone changes the spreadsheet through the google sheets websiteyour script can update the spreadsheet object to match the online data by calling the refresh(methodss refresh(this will refresh not only the spreadsheet object' attributes but also the data in the sheet objects it contains the changes you make to the spreadsheet object will be reflected in the online spreadsheet in real time downloading and uploading spreadsheets you can download google sheets spreadsheet in number of formatsexcelopenofficecsvtsvand pdf you can also download it as zip file containing html files of the spreadsheet' data ezsheets contains functions for each of these optionsimport ezsheets ss ezsheets spreadsheet(' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu'ss title 'class datass downloadasexcel(downloads the spreadsheet as an excel file 'class_data xlsxss downloadasods(downloads the spreadsheet as an openoffice file 'class_data odsss downloadascsv(only downloads the first sheet as csv file 'class_data csvss downloadastsv(only downloads the first sheet as tsv file 'class_data tsvss downloadaspdf(downloads the spreadsheet as pdf 'class_data pdfss downloadashtml(downloads the spreadsheet as zip of html files 'class_data zipnote that files in the csv and tsv formats can contain only one sheetthereforeif you download google sheets spreadsheet in this formatyou working with google sheets |
2,818 | the sheet object' index attribute to see "creating and deleting sheetson page for information on how to do this the download functions all return string of the downloaded file' filename you can also specify your own filename for the spreadsheet by passing the new filename to the download functionss downloadasexcel('a_different_filename xlsx''a_different_filename xlsxthe function should return the updated filename deleting spreadsheets to delete spreadsheetcall the delete(methodimport ezsheets ss ezsheets createspreadsheet('delete me'create the spreadsheet ezsheets listspreadsheets(confirm that we've created spreadsheet {' acw nnjszbldbhygvv kpsl djmgv zjzllsoz_mrk''delete me'ss delete(delete the spreadsheet ezsheets listspreadsheets({the delete(method will move your spreadsheet to the trash folder on your google drive you can view the contents of your trash folder at drive google com/drive/trash to permanently delete your spreadsheetpass true for the permanent keyword argumentss delete(permanent=truein generalpermanently deleting your spreadsheets is not good ideabecause it would be impossible to recover spreadsheet that bug in your script accidentally deleted even free google drive accounts have gigabytes of storage availableso you most likely don' need to worry about freeing up space sheet objects spreadsheet object will have one or more sheet objects the sheet objects represent the rows and columns of data in each sheet you can access these sheets using the square brackets operator and an integer index the spreadsheet object' sheets attribute holds tuple of sheet objects in the order in which they appear in the spreadsheet to access the sheet objects in spreadsheetenter the following into the interactive shellimport ezsheets ss ezsheets spreadsheet(' -jx ne k_vqi so-taxofbxx_ tujwnkpc ljeu'ss sheets the sheet objects in this spreadsheetin order |
2,819 | ss sheets[ gets the first sheet object in this spreadsheet ss[ also gets the first sheet object in this spreadsheet you can also obtain sheet object with the square brackets operator and string of the sheet' name the spreadsheet object' sheettitles attribute holds tuple of all the sheet titles for exampleenter the following into the interactive shellss sheettitles the titles of all the sheet objects in this spreadsheet ('classes''resources'ss['classes'sheets can also be accessed by title once you have sheet objectyou can read data from and write data to it using the sheet object' methodsas explained in the next section reading and writing data just as in excelgoogle sheets worksheets have columns and rows of cells containing data you can use the square brackets operator to read and write data from and to these cells for exampleto create new spreadsheet and add data to itenter the following into the interactive shellimport ezsheets ss ezsheets createspreadsheet('my spreadsheet'sheet ss[ get the first sheet in this spreadsheet sheet title 'sheet sheet ss[ sheet[' ''nameset the value in cell sheet[' ''agesheet[' ''favorite moviesheet[' 'read the value in cell 'namesheet[' 'empty cells return blank string 'sheet[ column row is the same address as 'agesheet[' ''alicesheet[' ' sheet[' ''robocopthese instructions should produce google sheets spreadsheet that looks like figure - working with google sheets |
2,820 | multiple users can update sheet simultaneously to refresh the local data in the sheet objectcall its refresh(methodsheet refresh(all of the data in the sheet object is loaded when the spreadsheet object is first loadedso the data is read instantly howeverwriting values to the online spreadsheet requires network connection and can take about second if you have thousands of cells to updateupdating them one at time might be quite slow column and row addressing cell addressing works in google sheets just like in excel the only difference is thatunlike python' -based list indexesgoogle sheets have -based columns and rowsthe first column or row is at index not you can convert the ' string-style address to the (columnrowtuplestyle address (and vice versawith the convertaddress(function the getcolumnletterof(and getcolumnnumberof(functions will also convert column address between letters and numbers enter the following into the interactive shellimport ezsheets ezsheets convertaddress(' 'converts addresses ( ezsheets convertaddress( and converts them backtoo ' ezsheets getcolumnletterof( 'bezsheets getcolumnnumberof(' ' ezsheets getcolumnletterof( 'alk |
2,821 | the ' string-style addresses are convenient if you're typing addresses into your source code but the (columnrowtuple-style addresses are convenient if you're looping over range of addresses and need numeric form for the column the convertaddress()getcolumnletterof()and getcolumnnumberof(functions are helpful when you need to convert between the two formats reading and writing entire columns and rows as mentionedwriting data one cell at time can often take too long fortunatelyezsheets has sheet methods for reading and writing entire columns and rows at the same time the getcolumn()getrow()updatecolumn()and updaterow(methods willrespectivelyread and write columns and rows these methods make requests to the google sheets servers to update the spreadsheetso they require that you be connected to the internet in this section' examplewe'll upload producesales xlsx from the last to google sheets the first eight rows look like table - table - the first eight rows of the producesales xlsx spreadsheet produce cost per pound pounds sold total potatoes okra fava beans watermelon garlic parsnips asparagus to upload this spreadsheetenter the following into the interactive shellimport ezsheets ss ezsheets upload('producesales xlsx'sheet ss[ sheet getrow( the first row is row not row ['produce''cost per pound''pounds sold''total'''''sheet getrow( ['potatoes'' '' '' '''''columnone sheet getcolumn( sheet getcolumn( ['produce''potatoes''okra''fava beans''watermelon''garlic'--snipsheet getcolumn(' 'same result as getcolumn( ['produce''potatoes''okra''fava beans''watermelon''garlic'--snipsheet getrow( working with google sheets |
2,822 | sheet updaterow( ['pumpkin'' '' '' ']sheet getrow( ['pumpkin'' '' '' '''''columnone sheet getcolumn( for ivalue in enumerate(columnone)make the python list contain uppercase stringscolumnone[ivalue upper(sheet updatecolumn( columnoneupdate the entire column in one request the getrow(and getcolumn(functions retrieve the data from every cell in specific row or column as list of values note that empty cells become blank string values in the list you can pass getcolumn(either column number or letter to tell it to retrieve specific column' data the previous example shows that getcolumn( and getcolumn(' 'return the same list the updaterow(and updatecolumn(functions will overwrite all the data in the row or columnrespectivelywith the list of values passed to the function in this examplethe third row initially contains information about okrabut the updaterow(call replaces it with data about pumpkin call sheet getrow( again to view the new values in the third row nextlet' update the "producesalesspreadsheet updating cells one at time is slow if you have many cells to update getting column or row as listupdating the listand then updating the entire column or row with the list is much fastersince all the changes can be made in one request to get all of the rows at oncecall the getrows(method to return list of lists the inner lists inside the outer list each represent single row of the sheet you can modify the values in this data structure to change the produce namepounds soldand total cost of some of the rows then you pass it to the updaterows(method by entering the following into the interactive shellrows sheet getrows(get every row in the spreadsheet rows[ examine the values in the first row ['produce''cost per pound''pounds sold''total'''''rows[ ['potatoes'' '' '' '''''rows[ ][ 'pumpkinchange the produce name rows[ ['pumpkin'' '' '' '''''rows[ ['okra'' '' '' '''''rows[ ][ ' change the pounds sold rows[ ][ ' change the total rows[ ['okra'' '' '' '''''sheet updaterows(rowsupdate the online spreadsheet with the changes you can update the entire sheet in single request by passing updaterows(the list of lists returned from getrows()amended with the changes made to rows and |
2,823 | this is because the uploaded sheet has column count of but we have only columns of data you can read the number of rows and columns in sheet with the rowcount and columncount attributes then by setting these valuesyou can change the size of the sheet sheet rowcount the number of rows in the sheet sheet columncount the number of columns in the sheet sheet columncount change the number of columns to sheet columncount now the number of columns in the sheet is these instructions should delete the fifth and sixth columns of the "producesalesspreadsheetas shown in figure - figure - the sheet before (leftand after (rightchanging the column count to according to google sheets spreadsheets can have up to million cells in them howeverit' good idea to make sheets only as big as you need to minimize the time it takes to update and refresh the data creating and deleting sheets all google sheets spreadsheets start with single sheet named "sheet you can add additional sheets to the end of the list of sheets with the createsheet(methodto which you pass string to use as the new sheet' title an optional second argument can specify the integer index of the new sheet to create spreadsheet and then add new sheets to itenter the following into the interactive shellimport ezsheets ss ezsheets createspreadsheet('multiple sheets'ss sheettitles ('sheet ',working with google sheets |
2,824 | sheets ss createsheet('eggs'create another new sheet ss sheettitles ('sheet ''spam''eggs'ss createsheet('bacon' create sheet at index in the list of sheets ss sheettitles ('bacon''sheet ''spam''eggs'these instructions add three new sheets to the spreadsheet"bacon,"spam,and "eggs(in addition to the default "sheet "the sheets in spreadsheet are orderedand new sheets go to the end of the list unless you pass second argument to createsheet(specifying the sheet' index hereyou create the sheet titled "baconat index making "baconthe first sheet in the spreadsheet and displacing the other three sheets by one position this is similar to the behavior of the insert(list method you can see the new sheets on the tabs at the bottom of the screenas shown in figure - figure - the "multiple sheetsspreadsheet after adding sheets "spam,"eggs,and "baconthe sheet object' delete(method will delete the sheet from the spreadsheet if you want to keep the sheet but delete the data it containscall the clear(method to clear all the cells and make it blank sheet enter the following into the interactive shellss sheettitles ('bacon''sheet ''spam''eggs'ss[ delete(delete the sheet at index the "baconsheet ss sheettitles ('sheet ''spam''eggs' |
2,825 | ss sheettitles ('sheet ''eggs'sheet ss['eggs'assign variable to the "eggssheet sheet delete(delete the "eggssheet ss sheettitles ('sheet ',ss[ clear(clear all the cells on the "sheet sheet ss sheettitles the "sheet sheet is empty but still exists ('sheet ',deleting sheets is permanentthere' no way to recover the data howeveryou can back up sheets by copying them to another spreadsheet with the copyto(methodas explained in the next section copying sheets every spreadsheet object has an ordered list of the sheet objects it containsand you can use this list to reorder the sheets (as shown in the previous sectionor copy them to other spreadsheets to copy sheet object to another spreadsheet objectcall the copyto(method pass it the destination spreadsheet object as an argument to create two spreadsheets and copy the first spreadsheet' data to the other sheetenter the following into the interactive shellimport ezsheets ss ezsheets createspreadsheet('first spreadsheet'ss ezsheets createspreadsheet('second spreadsheet'ss [ ss [ updaterow( ['some''data''in''the''first''row']ss [ copyto(ss copy the ss ' sheet to the ss spreadsheet ss sheettitles ss now contains copy of ss ' sheet ('sheet ''copy of sheet 'note that since the destination spreadsheet (ss in the previous examplealready had sheet named sheet the copied sheet will be named copy of sheet copied sheets appear at the end of the list of the destination spreadsheet' sheets if you wishyou can change their index attribute to reorder them in the new spreadsheet working with google sheets quotas because google sheets is onlineit' easy to share sheets among multiple users who can all access the sheets simultaneously howeverthis also means that reading and updating the sheets will be slower than reading and updating excel files stored locally on your hard drive in additiongoogle sheets has limits on how many read and write operations you can perform according to google' developer guidelinesusers are restricted to creating new spreadsheets dayand free google accounts can working with google sheets |
2,826 | exceed this quota will raise the googleapiclient errors httperror "quota exceeded for quota groupexception ezsheets will automatically catch this exception and retry the request when this happensthe function calls to read or write data will take several seconds (or even full minute or twobefore they return if the request continues to fail (which is possible if another script using the same credentials is also making requests)ezsheets will re-raise this exception this means thaton occasionyour ezsheets method calls may take several seconds before they return if you want to view your api usage or increase your quotago to the iam admin quotas page at developers google com/quotasto learn about paying for increased usage if you' rather just deal with the httperror exceptions yourselfyou can set ezsheets ignore_quota to trueand ezsheet' methods will raise these exceptions when it encounters them summary google sheets is popular online spreadsheet application that runs in your browser using the ezsheets third-party moduleyou can downloadcreatereadand modify spreadsheets ezsheets represents spreadsheets as spreadsheet objectseach of which contains an ordered list of sheet objects each sheet has columns and rows of data that you can read and update in several ways while google sheets makes sharing data and cooperative editing easyits main disadvantage is speedyou must update spreadsheets with web requestswhich can take few seconds to execute but for most purposesthis speed restriction won' affect python scripts using ezsheets google sheets also limits how often you can make changes for complete documentation of ezsheet' featuresvisit readthedocs iopractice questions what three files do you need for ezsheets to access google sheetswhat two types of objects does ezsheets havehow can you create an excel file from google sheet spreadsheethow can you create google sheet spreadsheet from an excel filethe ss variable contains spreadsheet object what code will read data from the cell in sheet titled "students"how can you find the column letters for column how can you find out how many rows and columns sheet hashow do you delete spreadsheetis this deletion permanent |
2,827 | what functions will create new spreadsheet object and new sheet objectrespectively what will happen ifby making frequent read and write requests with ezsheetsyou exceed your google account' quotapractice projects for practicewrite programs to do the following tasks downloading google forms data google forms allows you to create simple online forms that make it easy to collect information from people the information they enter into the form is stored in google sheet for this projectwrite program that can automatically download the form information that users have submitted go to add fields to the form that ask the user for name and email address then click the send button in the upper right to get link to your new formsuch as responses into this form on the "responsestab of your formclick the green create spreadsheet button to create google sheets spreadsheet that will hold the responses that users submit you should see your example responses in the first rows of this spreadsheet then write python script using ezsheets to collect list of the email addresses on this spreadsheet converting spreadsheets to other formats you can use google sheets to convert spreadsheet file into other formats write script that passes submitted file to upload(once the spreadsheet has uploaded to google sheetsdownload it using downloadasexcel()downloadasods()and other such functions to create copy of the spreadsheet in these other formats finding mistakes in spreadsheet after long day at the bean-counting officei've finished spreadsheet with all the bean totals and uploaded them to google sheets the spreadsheet is publicly viewable (but not editableyou can get this spreadsheet with the following codeimport ezsheets ss ezsheets spreadsheet(' jdzedvsih tmzxccyy zxrh-ellrwq _yyizreob jg'you can look at this spreadsheet in your browser by going to google com/spreadsheets/ / jdzedvsih tmzxccyy zxrh-ellrwq _yyizreob jg /edit?usp=sharingthe columns of the first sheet in this spreadsheet are "beans per jar,"jars,and "total beans the "total beanscolumn is working with google sheets |
2,828 | howeverthere is mistake in one of the , rows in this sheet that' too many rows to check by hand luckilyyou can write script that checks the totals as hintyou can access the individual cells in row with ss[ getrow (rownum)where ss is the spreadsheet object and rownum is the row number remember that row numbers in google sheets begin at not the cell values will be stringsso you'll need to convert them to integers so your program can work with them the expression int(ss[ getrow( )[ ]int(ss[ getrow( )[ ]=int(ss[ getrow( )[ ]evaluates to true if the row has the correct total put this code in loop to identify which row in the sheet has the incorrect total |
2,829 | working with pdf and word documents pdf and word documents are binary fileswhich makes them much more complex than plaintext files in addition to textthey store lots of fontcolorand layout information if you want your programs to read or write to pdfs or word documentsyou'll need to do more than simply pass their filenames to open(fortunatelythere are python modules that make it easy for you to interact with pdfs and word documents this will cover two such modulespypdf and python-docx pdf documents pdf stands for portable document format and uses the pdf file extension although pdfs support many featuresthis will focus on the two things you'll be doing most often with themreading text content from pdfs and crafting new pdfs from existing documents |
2,830 | important that you install this version because future versions of pypdf may be incompatible with the code to install itrun pip install --user pypdf =from the command line this module name is case sensitiveso make sure the is lowercase and everything else is uppercase (check out appendix for full details about installing third-party modules if the module was installed correctlyrunning import pypdf in the interactive shell shouldn' display any errors the proble atic pdf form at while pdf files are great for laying out text in way that' easy for people to print and readthey're not straightforward for software to parse into plaintext as resultpypdf might make mistakes when extracting text from pdf and may even be unable to open some pdfs at all there isn' much you can do about thisunfortunately pypdf may simply be unable to work with some of your particular pdf files that saidi haven' found any pdf files so far that can' be opened with pypdf extracting text from pdfs pypdf does not have way to extract imageschartsor other media from pdf documentsbut it can extract text and return it as python string to start learning how pypdf workswe'll use it on the example pdf shown in figure - figure - the pdf page that we will be extracting text from |
2,831 | the following into the interactive shellimport pypdf pdffileobj open('meetingminutes pdf''rb'pdfreader pypdf pdffilereader(pdffileobjpdfreader numpages pageobj pdfreader getpage( pageobj extracttext('ooffffiicciiaall bbooaarrdd mmiinnuutteess meeting of march \ the board of elementary and secondary education shall provide leadership and create policies for education that expand opportunities for childrenempower families and communitiesand advance louisiana in an increasingly competitive global market board of elementary and secondary education pdffileobj close(firstimport the pypdf module then open meetingminutes pdf in read binary mode and store it in pdffileobj to get pdffilereader object that represents this pdfcall pypdf pdffilereader(and pass it pdffileobj store this pdffilereader object in pdfreader the total number of pages in the document is stored in the numpages attribute of pdffilereader object the example pdf has pagesbut let' extract text from only the first page to extract text from pageyou need to get page objectwhich represents single page of pdffrom pdffilereader object you can get page object by calling the getpage(method on pdffilereader object and passing it the page number of the page you're interested in--in our case pypdf uses zero-based index for getting pagesthe first page is page the second is page and so on this is always the caseeven if pages are numbered differently within the document for examplesay your pdf is three-page excerpt from longer reportand its pages are numbered and to get the first page of this documentyou would want to call pdfreader getpage( )not getpage( or getpage( once you have your page objectcall its extracttext(method to return string of the page' text the text extraction isn' perfectthe text charles "chasroemerpresident from the pdf is absent from the string returned by extracttext()and the spacing is sometimes off stillthis approximation of the pdf text content may be good enough for your program decrypting pdfs some pdf documents have an encryption feature that will keep them from being read until whoever is opening the document provides password enter the following into the interactive shell with the pdf you downloadedwhich has been encrypted with the password rosebudimport pypdf pdfreader pypdf pdffilereader(open('encrypted pdf''rb')working with pdf and word documents |
2,832 | true pdfreader getpage( traceback (most recent call last)file ""line in pdfreader getpage(--snip-file " :\python \lib\site-packages\pypdf \pdf py"line in getobject raise utils pdfreaderror("file has not been decrypted"pypdf utils pdfreaderrorfile has not been decrypted pdfreader pypdf pdffilereader(open('encrypted pdf''rb')pdfreader decrypt('rosebud' pageobj pdfreader getpage( all pdffilereader objects have an isencrypted attribute that is true if the pdf is encrypted and false if it isn' any attempt to call function that reads the file before it has been decrypted with the correct password will result in an error note due to bug in pypdf version calling getpage(on an encrypted pdf before calling decrypt(on it causes future getpage(calls to fail with the following errorindexerrorlist index out of range this is why our example reopened the file with new pdffilereader object to read an encrypted pdfcall the decrypt(function and pass the password as string after you call decrypt(with the correct passwordyou'll see that calling getpage(no longer causes an error if given the wrong passwordthe decrypt(function will return and getpage(will continue to fail note that the decrypt(method decrypts only the pdffilereader objectnot the actual pdf file after your program terminatesthe file on your hard drive remains encrypted your program will have to call decrypt(again the next time it is run creating pdfs pypdf ' counterpart to pdffilereader is pdffilewriterwhich can create new pdf files but pypdf cannot write arbitrary text to pdf like python can do with plaintext files insteadpypdf ' pdf-writing capabilities are limited to copying pages from other pdfsrotating pagesoverlaying pagesand encrypting files pypdf doesn' allow you to directly edit pdf insteadyou have to create new pdf and then copy content over from an existing document the examples in this section will follow this general approach open one or more existing pdfs (the source pdfsinto pdffilereader objects create new pdffilewriter object |
2,833 | copy pages from the pdffilereader objects into the pdffilewriter object finallyuse the pdffilewriter object to write the output pdf creating pdffilewriter object creates only value that represents pdf document in python it doesn' create the actual pdf file for thatyou must call the pdffilewriter' write(method the write(method takes regular file object that has been opened in write-binary mode you can get such file object by calling python' open(function with two argumentsthe string of what you want the pdf' filename to be and 'wbto indicate the file should be opened in write-binary mode if this sounds little confusingdon' worry--you'll see how this works in the following code examples copying pages you can use pypdf to copy pages from one pdf document to another this allows you to combine multiple pdf filescut unwanted pagesor reorder pages download meetingminutes pdf and meetingminutes pdf from com/automatestuff and place the pdfs in the current working directory enter the following into the interactive shellimport pypdf pdf file open('meetingminutes pdf''rb'pdf file open('meetingminutes pdf''rb'pdf reader pypdf pdffilereader(pdf filepdf reader pypdf pdffilereader(pdf filepdfwriter pypdf pdffilewriter(for pagenum in range(pdf reader numpages)pageobj pdf reader getpage(pagenumpdfwriter addpage(pageobjfor pagenum in range(pdf reader numpages)pageobj pdf reader getpage(pagenumpdfwriter addpage(pageobjpdfoutputfile open('combinedminutes pdf''wb'pdfwriter write(pdfoutputfilepdfoutputfile close(pdf file close(pdf file close(open both pdf files in read binary mode and store the two resulting file objects in pdf file and pdf file call pypdf pdffilereader(and pass it pdf file to get pdffilereader object for meetingminutes pdf call it again and pass it pdf file to get pdffilereader object for meetingminutes pdf then create new pdffilewriter objectwhich represents blank pdf document working with pdf and word documents |
2,834 | to the pdffilewriter object get the page object by calling getpage(on pdffilereader object then pass that page object to your pdffilewriter' addpage(method these steps are done first for pdf reader and then again for pdf reader when you're done copying pageswrite new pdf called combinedminutes pdf by passing file object to the pdffilewriter' write(method note pypdf cannot insert pages in the middle of pdffilewriter objectthe addpage(method will only add pages to the end you have now created new pdf file that combines the pages from meetingminutes pdf and meetingminutes pdf into single document remember that the file object passed to pypdf pdffilereader(needs to be opened in read-binary mode by passing 'rbas the second argument to open(likewisethe file object passed to pypdf pdffilewriter(needs to be opened in writebinary mode with 'wbrotating pages the pages of pdf can also be rotated in -degree increments with the rotateclockwise(and rotatecounterclockwise(methods pass one of the integers or to these methods enter the following into the interactive shellwith the meetingminutes pdf file in the current working directoryimport pypdf minutesfile open('meetingminutes pdf''rb'pdfreader pypdf pdffilereader(minutesfilepage pdfreader getpage( page rotateclockwise( {'/contents'[indirectobject( )indirectobject( )--snip-pdfwriter pypdf pdffilewriter(pdfwriter addpage(pageresultpdffile open('rotatedpage pdf''wb'pdfwriter write(resultpdffileresultpdffile close(minutesfile close(here we use getpage( to select the first page of the pdf and then we call rotateclockwise( on that page we write new pdf with the rotated page and save it as rotatedpage pdf the resulting pdf will have one pagerotated degrees clockwiseas shown in figure - the return values from rotateclockwise(and rotatecounterclockwise(contain lot of information that you can ignore |
2,835 | rotated degrees clockwise overlaying pages pypdf can also overlay the contents of one page over anotherwhich is useful for adding logotimestampor watermark to page with pythonit' easy to add watermarks to multiple files and only to pages your program specifies download watermark pdf from place the pdf in the current working directory along with meetingminutes pdf then enter the following into the interactive shellimport pypdf minutesfile open('meetingminutes pdf''rb'pdfreader pypdf pdffilereader(minutesfileminutesfirstpage pdfreader getpage( pdfwatermarkreader pypdf pdffilereader(open('watermark pdf''rb')minutesfirstpage mergepage(pdfwatermarkreader getpage( )pdfwriter pypdf pdffilewriter(pdfwriter addpage(minutesfirstpagefor pagenum in range( pdfreader numpages)pageobj pdfreader getpage(pagenumpdfwriter addpage(pageobjresultpdffile open('watermarkedcover pdf''wb'pdfwriter write(resultpdffileminutesfile close(resultpdffile close(working with pdf and word documents |
2,836 | getpage( to get page object for the first page and store this object in minutesfirstpage we then make pdffilereader object for watermark pdf and call mergepage(on minutesfirstpage the argument we pass to mergepage(is page object for the first page of watermark pdf now that we've called mergepage(on minutesfirstpageminutesfirstpage represents the watermarked first page we make pdffilewriter object and add the watermarked first page then we loop through the rest of the pages in meetingminutes pdf and add them to the pdffilewriter object finallywe open new pdf called watermarkedcover pdf and write the contents of the pdffilewriter to the new pdf figure - shows the results our new pdfwatermarkedcover pdfhas all the contents of the meetingminutes pdfand the first page is watermarked figure - the original pdf (left)the watermark pdf (center)and the merged pdf (rightencrypting pdfs pdffilewriter object can also add encryption to pdf document enter the following into the interactive shellimport pypdf pdffile open('meetingminutes pdf''rb'pdfreader pypdf pdffilereader(pdffilepdfwriter pypdf pdffilewriter(for pagenum in range(pdfreader numpages)pdfwriter addpage(pdfreader getpage(pagenum)pdfwriter encrypt('swordfish'resultpdf open('encryptedminutes pdf''wb'pdfwriter write(resultpdfresultpdf close(before calling the write(method to save to filecall the encrypt(method and pass it password string pdfs can have user password (allowing you to view the pdfand an owner password (allowing you to set permissions for printingcommentingextracting textand other featuresthe user password and owner password are the first and second arguments |
2,837 | it will be used for both passwords in this examplewe copied the pages of meetingminutes pdf to pdffilewriter object we encrypted the pdffilewriter with the password swordfishopened new pdf called encryptedminutes pdfand wrote the contents of the pdffilewriter to the new pdf before anyone can view encryptedminutes pdfthey'll have to enter this password you may want to delete the originalunencrypted meetingminutes pdf file after ensuring its copy was correctly encrypted projectcombining select pages from many pdfs say you have the boring job of merging several dozen pdf documents into single pdf file each of them has cover sheet as the first pagebut you don' want the cover sheet repeated in the final result even though there are lots of free programs for combining pdfsmany of them simply merge entire files together let' write python program to customize which pages you want in the combined pdf at high levelhere' what the program will do find all pdf files in the current working directory sort the filenames so the pdfs are added in order write each pageexcluding the first pageof each pdf to the output file in terms of implementationyour code will need to do the following call os listdir(to find all the files in the working directory and remove any non-pdf files call python' sort(list method to alphabetize the filenames create pdffilewriter object for the output pdf loop over each pdf filecreating pdffilereader object for it loop over each page (except the firstin each pdf file add the pages to the output pdf write the output pdf to file named allminutes pdf for this projectopen new file editor tab and save it as combinepdfs py step find all pdf files firstyour program needs to get list of all files with the pdf extension in the current working directory and sort them make your code look like the following#python combinepdfs py combines all the pdfs in the current working directory into into single pdf import pypdf os working with pdf and word documents |
2,838 | pdffiles [for filename in os listdir(')if filename endswith(pdf')pdffiles append(filenamepdffiles sort(key str lowerpdfwriter pypdf pdffilewriter(todoloop through all the pdf files todoloop through all the pages (except the firstand add them todosave the resulting pdf to file after the shebang line and the descriptive comment about what the program doesthis code imports the os and pypdf modules the os listdir('call will return list of every file in the current working directory the code loops over this list and adds only those files with the pdf extension to pdffiles afterwardthis list is sorted in alphabetical order with the key str lower keyword argument to sort( pdffilewriter object is created to hold the combined pdf pages finallya few comments outline the rest of the program step open each pdf now the program must read each pdf file in pdffiles add the following to your program#python combinepdfs py combines all the pdfs in the current working directory into single pdf import pypdf os get all the pdf filenames pdffiles [--snip-loop through all the pdf files for filename in pdffilespdffileobj open(filename'rb'pdfreader pypdf pdffilereader(pdffileobjtodoloop through all the pages (except the firstand add them todosave the resulting pdf to file for each pdfthe loop opens filename in read-binary mode by calling open(with 'rbas the second argument the open(call returns file objectwhich gets passed to pypdf pdffilereader(to create pdffilereader object for that pdf file |
2,839 | for each pdfyou'll want to loop over every page except the first add this code to your program#python combinepdfs py combines all the pdfs in the current working directory into single pdf import pypdf os --snip-loop through all the pdf files for filename in pdffiles--snip-loop through all the pages (except the firstand add them for pagenum in range( pdfreader numpages)pageobj pdfreader getpage(pagenumpdfwriter addpage(pageobjtodosave the resulting pdf to file the code inside the for loop copies each page object individually to the pdffilewriter object rememberyou want to skip the first page since pypdf considers to be the first pageyour loop should start at and then go up tobut not includethe integer in pdfreader numpages step save the results after these nested for loops are done loopingthe pdfwriter variable will contain pdffilewriter object with the pages for all the pdfs combined the last step is to write this content to file on the hard drive add this code to your program#python combinepdfs py combines all the pdfs in the current working directory into single pdf import pypdf os --snip-loop through all the pdf files for filename in pdffiles--snip-loop through all the pages (except the firstand add them for pagenum in range( pdfreader numpages)--snip-save the resulting pdf to file pdfoutput open('allminutes pdf''wb'working with pdf and word documents |
2,840 | pdfoutput close(passing 'wbto open(opens the output pdf fileallminutes pdfin writebinary mode thenpassing the resulting file object to the write(method creates the actual pdf file call to the close(method finishes the program ideas for similar programs being able to create pdfs from the pages of other pdfs will let you make programs that can do the followingcut out specific pages from pdfs reorder pages in pdf create pdf from only those pages that have some specific textidentified by extracttext(word documents python can create and modify word documentswhich have the docx file extensionwith the docx module you can install the module by running pip install --user - python-docx=(appendix has full details on installing third-party modules note when using pip to first install python-docxbe sure to install python-docxnot docx the package name docx is for different module that this book does not cover howeverwhen you are going to import the module from the python-docx packageyou'll need to run import docxnot import python-docx if you don' have wordlibreoffice writer and openoffice writer are free alternative applications for windowsmacosand linux that can be used to open docx files you can download them from organd python-docx is available at is version of word for macosthis will focus on word for windows compared to plaintextdocx files have lot of structure this structure is represented by three different data types in python-docx at the highest levela document object represents the entire document the document object contains list of paragraph objects for the paragraphs in the document ( new paragraph begins whenever the user presses enter or return while typing in word document each of these paragraph objects contains list of one or more run objects the single-sentence paragraph in figure - has four runs plain paragraph with some bold and some italic run run run figure - the run objects identified in paragraph object run |
2,841 | colorand other styling information associated with it style in word is collection of these attributes run object is contiguous run of text with the same style new run object is needed whenever the text style changes reading word documents let' experiment with the docx module download demo docx from nostarch com/automatestuff and save the document to the working directory then enter the following into the interactive shellimport docx doc docx document('demo docx'len(doc paragraphs doc paragraphs[ text 'document titledoc paragraphs[ text ' plain paragraph with some bold and some italiclen(doc paragraphs[ runs doc paragraphs[ runs[ text ' plain paragraph with some doc paragraphs[ runs[ text 'bolddoc paragraphs[ runs[ text and some doc paragraphs[ runs[ text 'italicat we open docx file in pythoncall docx document()and pass the filename demo docx this will return document objectwhich has paragraphs attribute that is list of paragraph objects when we call len(on doc paragraphsit returns which tells us that there are seven paragraph objects in this document each of these paragraph objects has text attribute that contains string of the text in that paragraph (without the style informationherethe first text attribute contains 'documenttitleand the second contains ' plain paragraph with some bold and some italiceach paragraph object also has runs attribute that is list of run objects run objects also have text attributecontaining just the text in that particular run let' look at the text attributes in the second paragraph object' plain paragraph with some bold and some italiccalling len(on this paragraph object tells us that there are four run objects the first run object contains ' plain paragraph with some thenthe text changes to bold styleso 'boldstarts new run object the text returns to an unbolded style after thatwhich results in third run objectand some finallythe fourth and last run object contains 'italicin an italic style with python-docxyour python programs will now be able to read the text from docx file and use it just like any other string value working with pdf and word documents |
2,842 | if you care only about the textnot the styling informationin the word documentyou can use the gettext(function it accepts filename of docx file and returns single string value of its text open new file editor tab and enter the following codesaving it as readdocx py#python import docx def gettext(filename)doc docx document(filenamefulltext [for para in doc paragraphsfulltext append(para textreturn '\njoin(fulltextthe gettext(function opens the word documentloops over all the paragraph objects in the paragraphs listand then appends their text to the list in fulltext after the loopthe strings in fulltext are joined together with newline characters the readdocx py program can be imported like any other module now if you just need the text from word documentyou can enter the followingimport readdocx print(readdocx gettext('demo docx')document title plain paragraph with some bold and some italic headinglevel intense quote first item in unordered list first item in ordered list you can also adjust gettext(to modify the string before returning it for exampleto indent each paragraphreplace the append(call in readdocx py with thisfulltext append(para textto add double space between paragraphschange the join(call code to thisreturn '\ \njoin(fulltextas you can seeit takes only few lines of code to write functions that will read docx file and return string of its content to your liking |
2,843 | in word for windowsyou can see the styles by pressing ctrl-altshift- to display the styles panewhich looks like figure - on macosyou can view the styles pane by clicking the view styles menu item figure - display the styles pane by pressing ctrlaltshift- on windows word and other word processors use styles to keep the visual presentation of similar types of text consistent and easy to change for exampleperhaps you want to set body paragraphs in -pointtimes new romanleft-justifiedragged-right text you can create style with these settings and assign it to all body paragraphs thenif you later want to change the presentation of all body paragraphs in the documentyou can just change the styleand all those paragraphs will be automatically updated for word documentsthere are three types of stylesparagraph styles can be applied to paragraph objectscharacter styles can be applied to run objectsand linked styles can be applied to both kinds of objects you can give both paragraph and run objects styles by setting their style attribute to string this string should be the name of style if style is set to nonethen there will be no style associated with the paragraph or run object the string values for the default word styles are as follows'normal'body text'body text 'body text 'caption'heading 'heading 'heading 'heading 'heading 'heading 'heading 'heading 'heading 'intense quote'list'list 'list 'list bullet'list bullet 'list bullet 'list continue'list continue 'list continue 'list number 'list number 'list number 'list paragraph'macrotext'no spacing'quote'subtitle'toc heading'titleworking with pdf and word documents |
2,844 | to the end of its name for exampleto set the quote linked style for paragraph objectyou would use paragraphobj style 'quote'but for run objectyou would use runobj style 'quote charin the current version of python-docx ()the only styles that can be used are the default word styles and the styles in the opened docx new styles cannot be created--though this may change in future versions of python-docx creating word documents with nondefault styles if you want to create word documents that use styles beyond the default onesyou will need to open word to blank word document and create the styles yourself by clicking the new style button at the bottom of the styles pane (figure - shows this on windowsthis will open the create new style from formatting dialogwhere you can enter the new style thengo back into the interactive shell and open this blank word document with docx document()using it as the base for your word document the name you gave this style will now be available to use with python-docx figure - the new style button (leftand the create new style from formatting dialog (rightrun attributes runs can be further styled using text attributes each attribute can be set to one of three valuestrue (the attribute is always enabledno matter what other styles are applied to the run)false (the attribute is always disabled)or none (defaults to whatever the run' style is set totable - lists the text attributes that can be set on run objects |
2,845 | attribute description bold the text appears in bold italic the text appears in italic underline the text is underlined strike the text appears with strikethrough double_strike the text appears with double strikethrough all_caps the text appears in capital letters small_caps the text appears in capital letterswith lowercase letters two points smaller shadow the text appears with shadow outline the text appears outlined rather than solid rtl the text is written right-to-left imprint the text appears pressed into the page emboss the text appears raised off the page in relief for exampleto change the styles of demo docxenter the following into the interactive shellimport docx doc docx document('demo docx'doc paragraphs[ text 'document titledoc paragraphs[ style the exact id may be different_paragraphstyle('title'id doc paragraphs[ style 'normaldoc paragraphs[ text ' plain paragraph with some bold and some italic(doc paragraphs[ runs[ textdoc paragraphs[ runs[ textdoc paragraphs[ runs[ textdoc paragraphs[ runs[ text(' plain paragraph with some ''bold'and some ''italic'doc paragraphs[ runs[ style 'quotechardoc paragraphs[ runs[ underline true doc paragraphs[ runs[ underline true doc save('restyled docx'herewe use the text and style attributes to easily see what' in the paragraphs in our document we can see that it' simple to divide paragraph into runs and access each run individually so we get the firstsecondand fourth runs in the second paragraphstyle each runand save the results to new document the words document title at the top of restyled docx will have the normal style instead of the title stylethe run object for the text plain paragraph with some will have the quotechar styleand the two run objects for the words bold working with pdf and word documents |
2,846 | the styles of paragraphs and runs look in restyled docx figure - the restyled docx file you can find more complete documentation on python-docx' use of styles at writing word documents enter the following into the interactive shellimport docx doc docx document(doc add_paragraph('helloworld!'doc save('helloworld docx'to create your own docx filecall docx document(to return newblank word document object the add_paragraph(document method adds new paragraph of text to the document and returns reference to the paragraph object that was added when you're done adding textpass filename string to the save(document method to save the document object to file this will create file named helloworld docx in the current working directory thatwhen openedlooks like figure - figure - the word document created using add_paragraph('helloworld!' |
2,847 | with the new paragraph' text or to add text to the end of an existing paragraphyou can call the paragraph' add_run(method and pass it string enter the following into the interactive shellimport docx doc docx document(doc add_paragraph('hello world!'paraobj doc add_paragraph('this is second paragraph 'paraobj doc add_paragraph('this is yet another paragraph 'paraobj add_run(this text is being added to the second paragraph 'doc save('multipleparagraphs docx'the resulting document will look like figure - note that the text this text is being added to the second paragraph was added to the paragraph object in paraobj which was the second paragraph added to doc the add_paragraph(and add_run(functions return paragraph and run objectsrespectivelyto save you the trouble of extracting them as separate step keep in mind that as of python-docx version new paragraph objects can be added only to the end of the documentand new run objects can be added only to the end of paragraph object the save(method can be called again to save the additional changes you've made figure - the document with multiple paragraph and run objects added both add_paragraph(and add_run(accept an optional second argument that is string of the paragraph or run object' style here' an exampledoc add_paragraph('helloworld!''title'this line adds paragraph with the text helloworldin the title style working with pdf and word documents |
2,848 | calling add_heading(adds paragraph with one of the heading styles enter the following into the interactive shelldoc docx document(doc add_heading('header ' doc add_heading('header ' doc add_heading('header ' doc add_heading('header ' doc add_heading('header ' doc save('headings docx'the arguments to add_heading(are string of the heading text and an integer from to the integer makes the heading the title stylewhich is used for the top of the document integers to are for various heading levelswith being the main heading and the lowest subheading the add_heading(function returns paragraph object to save you the step of extracting it from the document object as separate step the resulting headings docx file will look like figure - figure - the headings docx document with headings to adding line and page breaks to add line break (rather than starting whole new paragraph)you can call the add_break(method on the run object you want to have the break appear after if you want to add page break insteadyou need to pass the value docx enum text wd_break page as lone argument to add_break()as is done in the middle of the following exampledoc docx document(doc add_paragraph('this is on the first page!'doc paragraphs[ runs[ add_break(docx enum text wd_break pagedoc add_paragraph('this is on the second page!'doc save('twopage docx' |
2,849 | on the first page and this is on the second pageon the second even though there was still plenty of space on the first page after the text this is on the first page!we forced the next paragraph to begin on new page by inserting page break after the first run of the first paragraph adding pictures document objects have an add_picture(method that will let you add an image to the end of the document say you have file zophie png in the current working directory you can add zophie png to the end of your document with width of inch and height of centimeters (word can use both imperial and metric unitsby entering the followingdoc add_picture('zophie png'width=docx shared inches( )height=docx shared cm( )the first argument is string of the image' filename the optional width and height keyword arguments will set the width and height of the image in the document if left outthe width and height will default to the normal size of the image you'll probably prefer to specify an image' height and width in familiar units such as inches and centimetersso you can use the docx shared inches(and docx shared cm(functions when you're specifying the width and height keyword arguments creating pdfs from word documents the pypdf module doesn' allow you to create pdf documents directlybut there' way to generate pdf files with python if you're on windows and have microsoft word installed you'll need to install the pywin package by running pip install --user - pywin == with this and the docx moduleyou can create word documents and then convert them to pdfs with the following script open new file editor tabenter the following codeand save it as convertwordtopdf pythis script runs on windows onlyand you must have word installed import win com client install with "pip install pywin == import docx wordfilename 'your_word_document docxpdffilename 'your_pdf_filename pdfdoc docx document(code to create word document goes here doc save(wordfilenamewdformatpdf word' numeric code for pdfs wordobj win com client dispatch('word application'working with pdf and word documents |
2,850 | docobj saveas(pdffilenamefileformat=wdformatpdfdocobj close(wordobj quit(to write program that produces pdfs with your own contentyou must use the docx module to create word documentthen use the pywin package' win com client module to convert it to pdf replace the code to create word document goes here comment with docx function calls to create your own content for the pdf in word document this may seem like convoluted way to produce pdfsbut as it turns outprofessional software solutions are often just as complicated summary text information isn' just for plaintext filesin factit' pretty likely that you deal with pdfs and word documents much more often you can use the pypdf module to read and write pdf documents unfortunatelyreading text from pdf documents might not always result in perfect translation to string because of the complicated pdf file formatand some pdfs might not be readable at all in these casesyou're out of luck unless future updates to pypdf support additional pdf features word documents are more reliableand you can read them with the python-docx package' docx module you can manipulate text in word documents via paragraph and run objects these objects can also be given stylesthough they must be from the default set of styles or styles already in the document you can add new paragraphsheadingsbreaksand pictures to the documentthough only to the end many of the limitations that come with working with pdfs and word documents are because these formats are meant to be nicely displayed for human readersrather than easy to parse by software the next takes look at two other common formats for storing informationjson and csv files these formats are designed to be used by computersand you'll see that python can work with these formats much more easily practice questions string value of the pdf filename is not passed to the pypdf pdffilereader(function what do you pass to the function insteadwhat modes do the file objects for pdffilereader(and pdffilewriter(need to be opened inhow do you acquire page object for page from pdffilereader objectwhat pdffilereader variable stores the number of pages in the pdf documentif pdffilereader object' pdf is encrypted with the password swordfishwhat must you do before you can obtain page objects from it |
2,851 | what methods do you use to rotate pagewhat method returns document object for file named demo docxwhat is the difference between paragraph object and run objecthow do you obtain list of paragraph objects for document object that' stored in variable named doc what type of object has boldunderlineitalicstrikeand outline variables what is the difference between setting the bold variable to truefalseor none how do you create document object for new word document how do you add paragraph with the text 'hellothere!to document object stored in variable named doc what integers represent the levels of headings available in word documentspractice projects for practicewrite programs that do the following pdf paranoia using the os walk(function from write script that will go through every pdf in folder (and its subfoldersand encrypt the pdfs using password provided on the command line save each encrypted pdf with an _encrypted pdf suffix added to the original filename before deleting the original filehave the program attempt to read and decrypt the file to ensure that it was encrypted correctly thenwrite program that finds all encrypted pdfs in folder (and its subfoldersand creates decrypted copy of the pdf using provided password if the password is incorrectthe program should print message to the user and continue to the next pdf custom invitations as word documents say you have text file of guest names this guests txt file has one name per lineas followsprof plum miss scarlet col mustard al sweigart robocop write program that would generate word document with custom invitations that look like figure - since python-docx can use only those styles that already exist in the word documentyou will have to first add these styles to blank word file and then open that file with python-docx there should be one invitation working with pdf and word documents |
2,852 | break after the last paragraph of each invitation this wayyou will need to open only one word document to print all of the invitations at once figure - the word document generated by your custom invite script you can download sample guests txt file from /automatestuff brute-force pdf password breaker say you have an encrypted pdf that you have forgotten the password tobut you remember it was single english word trying to guess your forgotten password is quite boring task instead you can write program that will decrypt the pdf by trying every possible english word until it finds one that works this is called brute-force password attack download the text file dictionary txt from using the file-reading skills you learned in create list of word strings by reading this file then loop over each word in this listpassing it to the decrypt(method if this method returns the integer the password was wrong and your program should continue to the next password if decrypt(returns then your program should break out of the loop and print the hacked password you should try both the uppercase and lowercase form of each word (on my laptopgoing through all , uppercase and lowercase words from the dictionary file takes couple of minutes this is why you shouldn' use simple english word for your passwords |
2,853 | working with csv files nd json data in you learned how to extract text from pdf and word documents these files were in binary formatwhich required special python modules to access their data csv and json fileson the other handare just plaintext files you can view them in text editorsuch as mu but python also comes with the special csv and json moduleseach providing functions to help you work with these file formats csv stands for "comma-separated values,and csv files are simplified spreadsheets stored as plaintext files python' csv module makes it easy to parse csv files json (pronounced "jay-sawnor "jason"--it doesn' matter how because either way people will say you're pronouncing it wrongis format that stores information as javascript source code in plaintext files (json is short for javascript object notation you don' need to know the javascript programming language to use json filesbut the json format is useful to know because it' used in many web applications |
2,854 | each line in csv file represents row in the spreadsheetand commas separate the cells in the row for examplethe spreadsheet example xlsx from : ,apples, : ,cherries, : ,pears, : ,oranges, : ,apples, : ,bananas, : ,strawberries, will use this file for this interactive shell examples you can download example csv from text into text editor and save it as example csv csv files are simplelacking many of the features of an excel spreadsheet for examplecsv filesdon' have types for their values--everything is string don' have settings for font size or color don' have multiple worksheets can' specify cell widths and heights can' have merged cells can' have images or charts embedded in them the advantage of csv files is simplicity csv files are widely supported by many types of programscan be viewed in text editors (including mu)and are straightforward way to represent spreadsheet data the csv format is exactly as advertisedit' just text file of comma-separated values since csv files are just text filesyou might be tempted to read them in as string and then process that string using the techniques you learned in for examplesince each cell in csv file is separated by commamaybe you could just call split(','on each line of text to get the comma-separated values as list of strings but not every comma in csv file represents the boundary between two cells csv files also have their own set of escape characters to allow commas and other characters to be included as part of the values the split(method doesn' handle these escape characters because of these potential pitfallsyou should always use the csv module for reading and writing csv files |
2,855 | to read data from csv file with the csv moduleyou need to create reader object reader object lets you iterate over lines in the csv file enter the following into the interactive shellwith example csv in the current working directoryimport csv examplefile open('example csv'examplereader csv reader(examplefileexampledata list(examplereaderexampledata [[ : ''apples'' '][ : ''cherries'' '][ : ''pears'' '][ : ''oranges'' '][ : ''apples'' '][ : ''bananas'' '][ : ''strawberries'' ']the csv module comes with pythonso we can import it without having to install it first to read csv file with the csv modulefirst open it using the open(function just as you would any other text file but instead of calling the read(or readlines(method on the file object that open(returnspass it to the csv reader(function this will return reader object for you to use note that you don' pass filename string directly to the csv reader(function the most direct way to access the values in the reader object is to convert it to plain python list by passing it to list(using list(on this reader object returns list of listswhich you can store in variable like exampledata entering exampledata in the shell displays the list of lists now that you have the csv file as list of listsyou can access the value at particular row and column with the expression exampledata[row][col]where row is the index of one of the lists in exampledataand col is the index of the item you want from that list enter the following into the interactive shellexampledata[ ][ : exampledata[ ][ 'applesexampledata[ ][ ' exampledata[ ][ 'cherriesexampledata[ ][ 'strawberriesas you can see from the outputexampledata[ ][ goes into the first list and gives us the first stringexampledata[ ][ goes into the first list and gives us the third stringand so on working with csv files and json data |
2,856 | for large csv filesyou'll want to use the reader object in for loop this avoids loading the entire file into memory at once for exampleenter the following into the interactive shellimport csv examplefile open('example csv'examplereader csv reader(examplefilefor row in examplereaderprint('row #str(examplereader line_numstr(row)row # [ : ''apples'' 'row # [ : ''cherries'' 'row # [ : ''pears'' 'row # [ : ''oranges'' 'row # [ : ''apples'' 'row # [ : ''bananas'' 'row # [ : ''strawberries'' 'after you import the csv module and make reader object from the csv fileyou can loop through the rows in the reader object each row is list of valueswith each value representing cell the print(function call prints the number of the current row and the contents of the row to get the row numberuse the reader object' line_num variablewhich contains the number of the current line the reader object can be looped over only once to reread the csv fileyou must call csv reader to create reader object writer objects writer object lets you write data to csv file to create writer objectyou use the csv writer(function enter the following into the interactive shellimport csv outputfile open('output csv'' 'newline=''outputwriter csv writer(outputfileoutputwriter writerow(['spam''eggs''bacon''ham'] outputwriter writerow(['helloworld!''eggs''bacon''ham'] outputwriter writerow([ ] outputfile close(firstcall open(and pass it 'wto open file in write mode this will create the object you can then pass to csv writer(to create writer object on windowsyou'll also need to pass blank string for the open(function' newline keyword argument for technical reasons beyond the scope of this bookif you forget to set the newline argumentthe rows in output csv will be double-spacedas shown in figure - |
2,857 | file will be double-spaced the writerow(method for writer objects takes list argument each value in the list is placed in its own cell in the output csv file the return value of writerow(is the number of characters written to the file for that row (including newline charactersthis code produces an output csv file that looks like thisspam,eggs,bacon,ham "helloworld!",eggs,bacon,ham , , , notice how the writer object automatically escapes the comma in the value 'helloworld!with double quotes in the csv file the csv module saves you from having to handle these special cases yourself the delimiter and lineterminator keyword arguments say you want to separate cells with tab character instead of comma and you want the rows to be double-spaced you could enter something like the following into the interactive shellimport csv csvfile open('example tsv'' 'newline=''csvwriter csv writer(csvfiledelimiter='\ 'lineterminator='\ \ 'csvwriter writerow(['apples''oranges''grapes'] csvwriter writerow(['eggs''bacon''ham'] csvwriter writerow(['spam''spam''spam''spam''spam''spam'] csvfile close(this changes the delimiter and line terminator characters in your file the delimiter is the character that appears between cells on row by defaultthe delimiter for csv file is comma the line terminator is the working with csv files and json data |
2,858 | is newline you can change characters to different values by using the delimiter and lineterminator keyword arguments with csv writer(passing delimiter='\tand lineterminator='\ \nchanges the character between cells to tab and the character between rows to two newlines we then call writerow(three times to give us three rows this produces file named example tsv with the following contentsapples oranges grapes eggs bacon ham spam spam spam spam spam spam now that our cells are separated by tabswe're using the file extension tsvfor tab-separated values dictreader and dictwriter csv objects for csv files that contain header rowsit' often more convenient to work with the dictreader and dictwriter objectsrather than the reader and writer objects the reader and writer objects read and write to csv file rows by using lists the dictreader and dictwriter csv objects perform the same functions but use dictionaries insteadand they use the first row of the csv file as the keys of these dictionaries go to header csv file this file is the same as example csv except it has timestampfruitand quantity as the column headers in the first row to read the fileenter the following into the interactive shellimport csv examplefile open('examplewithheader csv'exampledictreader csv dictreader(examplefilefor row in exampledictreaderprint(row['timestamp']row['fruit']row['quantity'] : apples : cherries : pears : oranges : apples : bananas : strawberries inside the loopdictreader object sets row to dictionary object with keys derived from the headers in the first row (welltechnicallyit sets row to an ordereddict objectwhich you can use in the same way as dictionarythe difference between them is beyond the scope of this book using dictreader object means you don' need additional code to skip the first row' header informationsince the dictreader object does this for you |
2,859 | column headers in the first rowthe dictreader object would use : ''apples'and ' as the dictionary keys to avoid thisyou can supply the dictreader(function with second argument containing made-up header namesimport csv examplefile open('example csv'exampledictreader csv dictreader(examplefile['time''name''amount']for row in exampledictreaderprint(row['time']row['name']row['amount'] : apples : cherries : pears : oranges : apples : bananas : strawberries because example csv' first row doesn' have any text for the heading of each columnwe created our own'time''name'and 'amountdictwriter objects use dictionaries to create csv files import csv outputfile open('output csv'' 'newline=''outputdictwriter csv dictwriter(outputfile['name''pet''phone']outputdictwriter writeheader(outputdictwriter writerow({'name''alice''pet''cat''phone'' '} outputdictwriter writerow({'name''bob''phone'' - '} outputdictwriter writerow({'phone'' - ''name''carol''pet''dog'} outputfile close(if you want your file to contain header rowwrite that row by calling writeheader(otherwiseskip calling writeheader(to omit header row from the file you then write each row of the csv file with writerow(method callpassing dictionary that uses the headers as keys and contains the data to write to the file the output csv file this code creates looks like thisname,pet,phone alice,cat, - bob,, - carol,dog, - working with csv files and json data |
2,860 | passed to writerow(doesn' matterthey're written in the order of the keys given to dictwriter(for exampleeven though you passed the phone key and value before the name and pet keys and values in the fourth rowthe phone number still appeared last in the output notice also that any missing keyssuch as 'petin {'name''bob''phone'' - '}will simply be empty in the csv file projectremoving the header from csv files say you have the boring job of removing the first line from several hundred csv files maybe you'll be feeding them into an automated process that requires just the data and not the headers at the top of the columns you could open each file in exceldelete the first rowand resave the file--but that would take hours let' write program to do it instead the program will need to open every file with the csv extension in the current working directoryread in the contents of the csv fileand rewrite the contents without the first row to file of the same name this will replace the old contents of the csv file with the newheadless contents warning as alwayswhenever you write program that modifies filesbe sure to back up the files firstjust in case your program does not work the way you expect it to you don' want to accidentally erase your original files at high levelthe program must do the following find all the csv files in the current working directory read in the full contents of each file write out the contentsskipping the first lineto new csv file at the code levelthis means the program will need to do the following loop over list of files from os listdir()skipping the non-csv files create csv reader object and read in the contents of the fileusing the line_num attribute to figure out which line to skip create csv writer object and write out the read-in data to the new file for this projectopen new file editor window and save it as removecsvheader py step loop through each csv file the first thing your program needs to do is loop over list of all csv filenames for the current working directory make your removecsvheader py look like this#python removecsvheader py removes the header from all csv files in the current |
2,861 | import csvos os makedirs('headerremoved'exist_ok=trueloop through every file in the current working directory for csvfilename in os listdir(')if not csvfilename endswith(csv')continue skip non-csv files print('removing header from csvfilename 'todoread the csv file in (skipping first rowtodowrite out the csv file the os makedirs(call will create headerremoved folder where all the headless csv files will be written for loop on os listdir('gets you partway therebut it will loop over all files in the working directoryso you'll need to add some code at the start of the loop that skips filenames that don' end with csv the continue statement makes the for loop move on to the next filename when it comes across non-csv file just so there' some output as the program runsprint out message saying which csv file the program is working on thenadd some todo comments for what the rest of the program should do step read in the csv file the program doesn' remove the first line from the csv file ratherit creates new copy of the csv file without the first line since the copy' filename is the same as the original filenamethe copy will overwrite the original the program will need way to track whether it is currently looping on the first row add the following to removecsvheader py #python removecsvheader py removes the header from all csv files in the current working directory --snip-read the csv file in (skipping first rowcsvrows [csvfileobj open(csvfilenamereaderobj csv reader(csvfileobjfor row in readerobjif readerobj line_num = continue skip first row csvrows append(rowcsvfileobj close(todowrite out the csv file working with csv files and json data |
2,862 | line in the csv file it is currently reading another for loop will loop over the rows returned from the csv reader objectand all rows but the first will be appended to csvrows as the for loop iterates over each rowthe code checks whether readerobj line_num is set to if soit executes continue to move on to the next row without appending it to csvrows for every row afterwardthe condition will be always be falseand the row will be appended to csvrows step write out the csv file without the first row now that csvrows contains all rows but the first rowthe list needs to be written out to csv file in the headerremoved folder add the following to removecsvheader py#python removecsvheader py removes the header from all csv files in the current working directory --snip-loop through every file in the current working directory for csvfilename in os listdir(')if not csvfilename endswith(csv')continue skip non-csv files --snip-write out the csv file csvfileobj open(os path join('headerremoved'csvfilename)' 'newline=''csvwriter csv writer(csvfileobjfor row in csvrowscsvwriter writerow(rowcsvfileobj close(the csv writer object will write the list to csv file in headerremoved using csvfilename (which we also used in the csv readerthis will overwrite the original file once we create the writer objectwe loop over the sublists stored in csvrows and write each sublist to the file after the code is executedthe outer for loop will loop to the next filename from os listdir('when that loop is finishedthe program will be complete to test your programdownload removecsvheader zip from com/automatestuff and unzip it to folder run the removecsvheader py program in that folder the output will look like thisremoving header from naics_data_ csv removing header from naics_data_ csv --snip- |
2,863 | removing header from naics_data_ csv this program should print filename each time it strips the first line from csv file ideas for similar programs the programs that you could write for csv files are similar to the kinds you could write for excel filessince they're both spreadsheet files you could write programs to do the followingcompare data between different rows in csv file or between multiple csv files copy specific data from csv file to an excel fileor vice versa check for invalid data or formatting mistakes in csv files and alert the user to these errors read data from csv file as input for your python programs json and apis javascript object notation is popular way to format data as single human-readable string json is the native way that javascript programs write their data structures and usually resembles what python' pprint(function would produce you don' need to know javascript in order to work with json-formatted data here' an example of data formatted as json{"name""zophie""iscat"true"micecaught" "napstaken" "felineiq"nulljson is useful to knowbecause many websites offer json content as way for programs to interact with the website this is known as providing an application programming interface (apiaccessing an api is the same as accessing any other web page via url the difference is that the data returned by an api is formatted (with jsonfor examplefor machinesapis aren' easy for people to read many websites make their data available in json format facebooktwitteryahoogoogletumblrwikipediaflickrdata govredditimdbrotten tomatoeslinkedinand many other popular sites offer apis for programs to use some of these sites require registrationwhich is almost always free you'll have to find documentation for what urls your program needs to request in order to get the data you wantas well as the general format of the json data structures that are returned this documentation should be provided by whatever site is offering the apiif they have "developerspagelook for the documentation there working with csv files and json data |
2,864 | scrape raw data from websites (accessing apis is often more convenient than downloading web pages and parsing html with beautiful soup automatically download new posts from one of your social network accounts and post them to another account for exampleyou could take your tumblr posts and post them to facebook create "movie encyclopediafor your personal movie collection by pulling data from imdbrotten tomatoesand wikipedia and putting it into single text file on your computer you can see some examples of json apis in the resources at nostarch com/automatestuff json isn' the only way to format data into human-readable string there are many othersincluding xml (extensible markup language)toml (tom' obviousminimal language)yml (yet another markup language)ini (initialization)or even the outdated asn (abstract syntax notation oneformatsall of which provide structure for representing data as human-readable text this book won' cover thesebecause json has quickly become the most widely used alternate formatbut there are third-party python modules that readily handle them the json module python' json module handles all the details of translating between string with json data and python values for the json loads(and json dumps(functions json can' store every kind of python value it can contain values of only the following data typesstringsintegersfloatsbooleanslistsdictionariesand nonetype json cannot represent python-specific objectssuch as file objectscsv reader or writer objectsregex objectsor selenium webelement objects reading json with the loads(function to translate string containing json data into python valuepass it to the json loads(function (the name means "load string,not "loads "enter the following into the interactive shellstringofjsondata '{"name""zophie""iscat"true"micecaught" "felineiq"null}import json jsondataaspythonvalue json loads(stringofjsondatajsondataaspythonvalue {'iscat'true'micecaught' 'name''zophie''felineiq'noneafter you import the json moduleyou can call loads(and pass it string of json data note that json strings always use double quotes it will return that data as python dictionary python dictionaries are not |
2,865 | print jsondataaspythonvalue writing json with the dumps(function the json dumps(function (which means "dump string,not "dumps"will translate python value into string of json-formatted data enter the following into the interactive shellpythonvalue {'iscat'true'micecaught' 'name''zophie''felineiq'noneimport json stringofjsondata json dumps(pythonvaluestringofjsondata '{"iscat"true"felineiq"null"micecaught" "name""zophie}the value can only be one of the following basic python data typesdictionarylistintegerfloatstringbooleanor none projectfetching current weather data checking the weather seems fairly trivialopen your web browserclick the address bartype the url to weather website (or search for one and then click the link)wait for the page to loadlook past all the adsand so on actuallythere are lot of boring steps you could skip if you had program that downloaded the weather forecast for the next few days and printed it as plaintext this program uses the requests module from to download data from the web overallthe program does the following reads the requested location from the command line downloads json weather data from openweathermap org converts the string of json data to python data structure prints the weather for today and the next two days so the code will need to do the following join strings in sys argv to get the location call requests get(to download the weather data call json loads(to convert the json data to python data structure print the weather forecast for this projectopen new file editor window and save it as getopen weather py then visit sign up for free account to obtain an api keyalso called an app idwhich for the openweathermap service is string code that looks something like ' aba eyou don' need to pay for this service working with csv files and json data |
2,866 | the api key secretanyone who knows it can write scripts that use your account' usage quota step get location from the command line argument the input for this program will come from the command line make getopenweather py look like this#python getopenweather py prints the weather for location from the command line appid 'your_appid_hereimport jsonrequestssys compute location from command line arguments if len(sys argv print('usagegetopenweather py city_name -letter_country_code'sys exit(location join(sys argv[ :]tododownload the json data from openweathermap org' api todoload json data into python variable in pythoncommand line arguments are stored in the sys argv list the appid variable should be set to the api key for your account without this keyyour requests to the weather service will fail after the #shebang line and import statementsthe program will check that there is more than one command line argument (recall that sys argv will always have at least one elementsys argv[ ]which contains the python script' filename if there is only one element in the listthen the user didn' provide location on the command lineand "usagemessage will be provided to the user before the program ends the openweathermap service requires that the query be formatted as the city namea commaand two-letter country code (like "usfor the united statesyou can find list of these codes at /wiki/iso_ - _alpha- our script displays the weather for the first city listed in the retrieved json text unfortunatelycities that share namelike portlandoregonand portlandmainewill both be includedthough the json text will include longitude and latitude information to differentiate between the cities command line arguments are split on spaces the command line argument san franciscous would make sys argv hold ['getopenweather py''san''francisco,''us'thereforecall the join(method to join all the strings except for the first in sys argv store this joined string in variable named location |
2,867 | openweathermap org provides real-time weather information in json format first you must sign up for free api key on the site (this key is used to limit how frequently you make requests on their serverto keep their bandwidth costs down your program simply has to download the page at openweathermap org/data/ /forecast/daily? =&cnt= &appid=<api key>where is the name of the city whose weather you want and is your personal api key add the following to getopenweather py #python getopenweather py prints the weather for location from the command line --snip-download the json data from openweathermap org' api url ='appidresponse requests get(urlresponse raise_for_status(uncomment to see the raw json text#print(response texttodoload json data into python variable we have location from our command line arguments to make the url we want to accesswe use the % placeholder and insert whatever string is stored in location into that spot in the url string we store the result in url and pass url to requests get(the requests get(call returns response objectwhich you can check for errors by calling raise_for_status(if no exception is raisedthe downloaded text will be in response text step load json data and print weather the response text member variable holds large string of json-formatted data to convert this to python valuecall the json loads(function the json data will look something like this{'city'{'coord'{'lat' 'lon'- }'country''united states of america''id'' ''name''san francisco''population' }'cnt' 'cod'' ''list'[{'clouds' 'deg' 'dt' 'humidity' 'pressure' working with csv files and json data |
2,868 | 'temp'{'day' 'eve' 'max' 'min' 'morn' 'night' }'weather'[{'description''sky is clear''icon'' '--snip-you can see this data by passing weatherdata to pprint pprint(you may want to check these fields mean for examplethe online documentation will tell you that the after 'dayis the daytime temperature in kelvinnot celsius or fahrenheit the weather descriptions you want are after 'mainand 'descriptionto neatly print them outadd the following to getopenweather py python getopenweather py prints the weather for location from the command line --snip-load json data into python variable weatherdata json loads(response textprint weather descriptions weatherdata['list'print('current weather in % :(location)print( [ ]['weather'][ ]['main']'-' [ ]['weather'][ ]['description']print(print('tomorrow:'print( [ ]['weather'][ ]['main']'-' [ ]['weather'][ ]['description']print(print('day after tomorrow:'print( [ ]['weather'][ ]['main']'-' [ ]['weather'][ ]['description']notice how the code stores weatherdata['list'in the variable to save you some typing you use [ ] [ ]and [ to retrieve the dictionaries for todaytomorrowand the day after tomorrow' weatherrespectively each of these dictionaries has 'weatherkeywhich contains list value you're interested in the first list itema nested dictionary with several more keysat index herewe print the values stored in the 'mainand 'descriptionkeysseparated by hyphen when this program is run with the command line argument getopen weather py san franciscocathe output looks something like thiscurrent weather in san franciscocaclear sky is clear |
2,869 | clouds few clouds day after tomorrowclear sky is clear (the weather is one of the reasons like living in san francisco!ideas for similar programs accessing weather data can form the basis for many types of programs you can create similar programs to do the followingcollect weather forecasts for several campsites or hiking trails to see which one will have the best weather schedule program to regularly check the weather and send you frost alert if you need to move your plants indoors covers schedulingand explains how to send email pull weather data from multiple sites to show all at onceor calculate and show the average of the multiple weather predictions summary csv and json are common plaintext formats for storing data they are easy for programs to parse while still being human readableso they are often used for simple spreadsheets or web app data the csv and json modules greatly simplify the process of reading and writing to csv and json files the last few have taught you how to use python to parse information from wide variety of file formats one common task is taking data from variety of formats and parsing it for the particular information you need these tasks are often specific to the point that commercial software is not optimally helpful by writing your own scriptsyou can make the computer handle large amounts of data presented in these formats in you'll break away from data formats and learn how to make your programs communicate with you by sending emails and text messages practice questions what are some features excel spreadsheets have that csv spreadsheets don'twhat do you pass to csv reader(and csv writer(to create reader and writer objectswhat modes do file objects for reader and writer objects need to be opened inworking with csv files and json data |
2,870 | what method takes list argument and writes it to csv filewhat do the delimiter and lineterminator keyword arguments dowhat function takes string of json data and returns python data structurewhat function takes python data structure and returns string of json datapractice project for practicewrite program that does the following excel-to-csv converter excel can save spreadsheet to csv file with few mouse clicksbut if you had to convert hundreds of excel files to csvsit would take hours of clicking using the openpyxl module from write program that reads all the excel files in the current working directory and outputs them as csv files single excel file might contain multiple sheetsyou'll have to create one csv file per sheet the filenames of the csv files should be csvwhere is the filename of the excel file without the file extension (for example'spam_data'not 'spam_data xlsx'and is the string from the worksheet object' title variable this program will involve many nested for loops the skeleton of the program will look something like thisfor excelfile in os listdir(')skip non-xlsx filesload the workbook object for sheetname in wb get_sheet_names()loop through every sheet in the workbook sheet wb get_sheet_by_name(sheetnamecreate the csv filename from the excel filename and sheet title create the csv writer object for this csv file loop through every row in the sheet for rownum in range( sheet max_row )rowdata [append each cell to this list loop through each cell in the row for colnum in range( sheet max_column )append each cell' data to rowdata write the rowdata list to the csv file csvfile close(download the zip file excelspreadsheets zip from /automatestuff and unzip the spreadsheets into the same directory as your program you can use these as the files to test the program on |
2,871 | keeping timesche dul ing ta sksand aunching progr ams running programs while you're sitting at your computer is finebut it' also useful to have programs run without your direct supervision your computer' clock can schedule programs to run code at some specified time and date or at regular intervals for exampleyour program could scrape website every hour to check for changes or do cpu-intensive task at am while you sleep python' time and datetime modules provide these functions you can also write programs that launch other programs on schedule by using the subprocess and threading modules oftenthe fastest way to program is to take advantage of applications that other people have already written |
2,872 | your computer' system clock is set to specific datetimeand time zone the built-in time module allows your python programs to read the system clock for the current time the time time(and time sleep(functions are the most useful in the time module the time time(function the unix epoch is time reference commonly used in programming am on january coordinated universal time (utcthe time time(function returns the number of seconds since that moment as float value (recall that float is just number with decimal point this number is called an epoch timestamp for exampleenter the following into the interactive shellimport time time time( here ' calling time time(on december at : pm pacific standard time the return value is how many seconds have passed between the unix epoch and the moment time time(was called epoch timestamps can be used to profile codethat ismeasure how long piece of code takes to run if you call time time(at the beginning of the code block you want to measure and again at the endyou can subtract the first timestamp from the second to find the elapsed time between those two calls for exampleopen new file editor tab and enter the following programimport time def calcprod()calculate the product of the first , numbers product for in range( )product product return product starttime time time(prod calcprod( endtime time time( print('the result is % digits long (len(str(prod))) print('took % seconds to calculate (endtime starttime)at uwe define function calcprod(to loop through the integers from to , and return their product at vwe call time time(and store it in starttime right after calling calcprod()we call time time(again and store it in endtime we end by printing the length of the product returned by calcprod( and how long it took to run calcprod( |
2,873 | the result is digits long took seconds to calculate note another way to profile your code is to use the cprofile run(functionwhich provides much more informative level of detail than the simple time time(technique the cprofile run(function is explained at /profile html the return value from time time(is usefulbut not human-readable the time ctime(function returns string description of the current time you can also optionally pass the number of seconds since the unix epochas returned by time time()to get string value of that time enter the following into the interactive shellimport time time ctime('mon jun : : thismoment time time(time ctime(thismoment'mon jun : : the time sleep(function if you need to pause your program for whilecall the time sleep(function and pass it the number of seconds you want your program to stay paused enter the following into the interactive shellimport time for in range( ) print('tick' time sleep( print('tock' time sleep( tick tock tick tock tick tock time sleep( the for loop will print tick upause for second vprint tock wpause for second xprint tickpauseand so on until tick and tock have each been printed three times keeping timescheduling tasksand launching programs |
2,874 | release your program to execute other code--until after the number of seconds you passed to time sleep(has elapsed for exampleif you enter time sleep( yyou'll see that the next prompt (doesn' appear until seconds have passed rounding numbers when working with timesyou'll often encounter float values with many digits after the decimal to make these values easier to work withyou can shorten them with python' built-in round(functionwhich rounds float to the precision you specify just pass in the number you want to roundplus an optional second argument representing how many digits after the decimal point you want to round it to if you omit the second argumentround(rounds your number to the nearest whole integer enter the following into the interactive shellimport time now time time(now round(now round(now round(now after importing time and storing time time(in nowwe call round(now to round now to two digits after the decimalround(now to round to four digits after the decimaland round(nowto round to the nearest integer projectsuper stopwatch say you want to track how much time you spend on boring tasks you haven' automated yet you don' have physical stopwatchand it' surprisingly difficult to find free stopwatch app for your laptop or smartphone that isn' covered in ads and doesn' send copy of your browser history to marketers (it says it can do this in the license agreement you agreed to you did read the license agreementdidn' you?you can write simple stopwatch program yourself in python at high levelhere' what your program will do track the amount of time elapsed between presses of the enter keywith each key press starting new "lapon the timer print the lap numbertotal timeand lap time |
2,875 | find the current time by calling time time(and store it as timestamp at the start of the programas well as at the start of each lap keep lap counter and increment it every time the user presses enter calculate the elapsed time by subtracting timestamps handle the keyboardinterrupt exception so the user can press ctrl- to quit open new file editor tab and save it as stopwatch py step set up the program to track times the stopwatch program will need to use the current timeso you'll want to import the time module your program should also print some brief instructions to the user before calling input()so the timer can begin after the user presses enter then the code will start tracking lap times enter the following code into the file editorwriting todo comment as placeholder for the rest of the code#python stopwatch py simple stopwatch program import time display the program' instructions print('press enter to begin afterwardpress enter to "clickthe stopwatch press ctrl- to quit 'input(press enter to begin print('started 'starttime time time(get the first lap' start time lasttime starttime lapnum todostart tracking the lap times now that we've written the code to display the instructionsstart the first lapnote the timeand set our lap count to step track and print lap times now let' write the code to start each new lapcalculate how long the previous lap tookand calculate the total time elapsed since starting the stopwatch we'll display the lap time and total time and increase the lap count for each new lap add the following code to your program#python stopwatch py simple stopwatch program import time --snip-keeping timescheduling tasksand launching programs |
2,876 | tryv while trueinput( laptime round(time time(lasttime totaltime round(time time(starttime print('lap #% % (% )(lapnumtotaltimelaptime)end=''lapnum + lasttime time time(reset the last lap time except keyboardinterrupthandle the ctrl- exception to keep its error message from displaying print('\ndone 'if the user presses ctrl- to stop the stopwatchthe keyboardinterrupt exception will be raisedand the program will crash if its execution is not try statement to prevent crashingwe wrap this part of the program in try statement we'll handle the exception in the except clause zso when ctrl - is pressed and the exception is raisedthe program execution moves to the except clause to print doneinstead of the keyboardinterrupt error message until this happensthe execution is inside an infinite loop that calls input(and waits until the user presses enter to end lap when lap endswe calculate how long the lap took by subtracting the start time of the laplasttimefrom the current timetime time( we calculate the total time elapsed by subtracting the overall start time of the stopwatchstarttimefrom the current time since the results of these time calculations will have many digits after the decimal point (such as )we use the round(function to round the float value to two digits at and at ywe print the lap numbertotal time elapsedand the lap time since the user pressing enter for the input(call will print newline to the screenpass end='to the print(function to avoid double-spacing the output after printing the lap informationwe get ready for the next lap by adding to the count lapnum and setting lasttime to the current timewhich is the start time of the next lap ideas for similar programs time tracking opens up several possibilities for your programs although you can download apps to do some of these thingsthe benefit of writing programs yourself is that they will be free and not bloated with ads and useless features you could write similar programs to do the following create simple timesheet app that records when you type person' name and uses the current time to clock them in or out add feature to your program to display the elapsed time since process startedsuch as download that uses the requests module (see intermittently check how long program has been running and offer the user chance to cancel tasks that are taking too long |
2,877 | the time module is useful for getting unix epoch timestamp to work with but if you want to display date in more convenient formator do arithmetic with dates (for examplefiguring out what date was days ago or what date is days from now)you should use the datetime module the datetime module has its own datetime data type datetime values represent specific moment in time enter the following into the interactive shellimport datetime datetime datetime now( datetime datetime( dt datetime datetime( dt yeardt monthdt day ( dt hourdt minutedt second ( calling datetime datetime now( returns datetime object for the current date and timeaccording to your computer' clock this object includes the yearmonthdayhourminutesecondand microsecond of the current moment you can also retrieve datetime object for specific moment by using the datetime datetime(function wpassing it integers representing the yearmonthdayhourand second of the moment you want these integers will be stored in the datetime object' yearmonthday xhourminuteand second attributes unix epoch timestamp can be converted to datetime object with the datetime datetime fromtimestamp(function the date and time of the datetime object will be converted for the local time zone enter the following into the interactive shellimport datetimetime datetime datetime fromtimestamp( datetime datetime( datetime datetime fromtimestamp(time time()datetime datetime( calling datetime datetime fromtimestamp(and passing it returns datetime object for the moment , , seconds after the unix epoch passing time time()the unix epoch timestamp for the current momentreturns datetime object for the current moment so the expressions datetime datetime now(and datetime datetime fromtimestamp(time time()do the same thingthey both give you datetime object for the present moment you can compare datetime objects with each other using comparison operators to find out which one precedes the other the later datetime object is the "greatervalue enter the following into the interactive shellu halloween datetime datetime( newyears datetime datetime( oct datetime datetime( keeping timescheduling tasksand launching programs |
2,878 | true halloween newyears false newyears halloween true newyears !oct true make datetime object for the first moment (midnightof october and store it in halloween make datetime object for the first moment of january and store it in newyears then make another object for midnight on october and store it in oct comparing halloween and oct shows that they're equal comparing newyears and halloween shows that newyears is greater (laterthan halloween the timedelta data type the datetime module also provides timedelta data typewhich represents duration of time rather than moment in time enter the following into the interactive shellu delta datetime timedelta(days= hours= minutes= seconds= delta daysdelta secondsdelta microseconds ( delta total_seconds( str(delta' days : : to create timedelta objectuse the datetime timedelta(function the datetime timedelta(function takes keyword arguments weeksdayshoursminutessecondsmillisecondsand microseconds there is no month or year keyword argumentbecause " monthor " yearis variable amount of time depending on the particular month or year timedelta object has the total duration represented in dayssecondsand microseconds these numbers are stored in the dayssecondsand microseconds attributesrespectively the total_seconds(method will return the duration in number of seconds alone passing timedelta object to str(will return nicely formattedhuman-readable string representation of the object in this examplewe pass keyword arguments to datetime delta(to specify duration of days hours minutesand secondsand store the returned timedelta object in delta this timedelta object' days attributes stores and its seconds attribute stores ( hours minutesand secondsexpressed in secondsv calling total_seconds(tells us that days hours minutesand seconds is , seconds finallypassing the timedelta object to str(returns string that plainly describes the duration |
2,879 | datetime values for exampleto calculate the date , days from nowenter the following into the interactive shelldt datetime datetime now(dt datetime datetime( thousanddays datetime timedelta(days= dt thousanddays datetime datetime( firstmake datetime object for the current moment and store it in dt then make timedelta object for duration of , days and store it in thousanddays add dt and thousanddays together to get datetime object for the date , days from now python will do the date arithmetic to figure out that , days after december will be august this is useful because when you calculate , days from given dateyou have to remember how many days are in each month and factor in leap years and other tricky details the datetime module handles all of this for you timedelta objects can be added or subtracted with datetime objects or other timedelta objects using the and operators timedelta object can be multiplied or divided by integer or float values with the and operators enter the following into the interactive shellu oct st datetime datetime( aboutthirtyyears datetime timedelta(days= oct st datetime datetime( oct st aboutthirtyyears datetime datetime( oct st ( aboutthirtyyearsdatetime datetime( here we make datetime object for october and timedelta object for duration of about years (we're assuming days for each of those yearsv subtracting aboutthirtyyears from oct st gives us datetime object for the date years before october subtracting aboutthirtyyears from oct st returns datetime object for the date years before october pausing until specific date the time sleep(method lets you pause program for certain number of seconds by using while loopyou can pause your programs until specific date for examplethe following code will continue to loop until halloween import datetime import time halloween datetime datetime( while datetime datetime now(halloween time sleep( keeping timescheduling tasksand launching programs |
2,880 | computer doesn' waste cpu processing cycles simply checking the time over and over ratherthe while loop will just check the condition once per second and continue with the rest of the program after halloween (or whenever you program it to stopconverting datetime objects into strings epoch timestamps and datetime objects aren' very friendly to the human eye use the strftime(method to display datetime object as string (the in the name of the strftime(function stands for format the strftime(method uses directives similar to python' string formatting table - has full list of strftime(directives table - strftime(directives strftime(directive meaning % year with centuryas in ' % year without century' to ' ( to % month as decimal number' to ' % full month nameas in 'november% abbreviated month nameas in 'nov% day of the month' to ' % day of the year' to ' % day of the week' (sundayto ' (saturday% full weekday nameas in 'monday% abbreviated weekday nameas in 'mon% hour ( -hour clock)' to ' % hour ( -hour clock)' to ' % minute' to ' % second' to ' % 'amor 'pm%literal '%character pass strftime( custom format string containing formatting directives (along with any desired slashescolonsand so on)and strftime(will return the datetime object' information as formatted string enter the following into the interactive shelloct st datetime datetime( oct st strftime('% /% /% % :% :% ' : : oct st strftime('% :% % '' : pmoct st strftime("% of '% ""october of ' |
2,881 | in oct st passing strftime(the custom format string '% /% /% % :% :%sreturns string containing and separated by slashes and and separated by colons passing '% :%mpreturns ' : pm'and passing "% of '%yreturns "october of ' note that strftime(doesn' begin with datetime datetime converting strings into datetime objects if you have string of date informationsuch as : : or 'october 'and need to convert it to datetime objectuse the datetime datetime strptime(function the strptime(function is the inverse of the strftime(method custom format string using the same directives as strftime(must be passed so that strptime(knows how to parse and understand the string (the in the name of the strptime(function stands for parse enter the following into the interactive shellu datetime datetime strptime('october ''% % % 'datetime datetime( datetime datetime strptime( : : ''% /% /% % :% :% 'datetime datetime( datetime datetime strptime("october of ' ""% of '% "datetime datetime( datetime datetime strptime("november of ' ""% of '% "datetime datetime( to get datetime object from the string 'october 'pass that string as the first argument to strptime(and the custom format string that corresponds to 'october as the second argument the string with the date information must match the custom format string exactlyor python will raise valueerror exception review of python' time functions dates and times in python can involve quite few different data types and functions here' review of the three different types of values used to represent timea unix epoch timestamp (used by the time moduleis float or integer value of the number of seconds since am on january utc datetime object (of the datetime modulehas integers stored in the attributes yearmonthdayhourminuteand second timedelta object (of the datetime modulerepresents time durationrather than specific moment keeping timescheduling tasksand launching programs |
2,882 | this function returns an epoch timestamp float value of the current moment time sleep(secondsthis function stops the program for the number of seconds specified by the seconds argument datetime datetime(yearmonthdayhourminutesecondthis function returns datetime object of the moment specified by the arguments if hourminuteor second arguments are not providedthey default to time time(datetime datetime now(this function returns datetime object of the current moment this function returns datetime object of the moment represented by the epoch timestamp argument datetime datetime fromtimestamp(epochdatetime timedelta(weeksdayshoursminutessecondsmillisecondsmicrosecondsthis function returns timedelta object representing duration of time the function' keyword arguments are all optional and do not include month or year total_seconds(this method for timedelta objects returns the number of seconds the timedelta object represents strftime(formatthis method returns string of the time represented by the datetime object in custom format that' based on the format string see table - for the format details datetime datetime strptime(time_stringformatthis function returns datetime object of the moment specified by time_stringparsed using the format string argument see table - for the format details multithreading to introduce the concept of multithreadinglet' look at an example situation say you want to schedule some code to run after delay or at specific time you could add code like the following at the start of your programimport timedatetime starttime datetime datetime( while datetime datetime now(starttimetime sleep( print('program now starting on halloween '--snip-this code designates start time of october and keeps calling time sleep( until the start time arrives your program cannot do anything while waiting for the loop of time sleep(calls to finishit just sits around until halloween this is because python programs by default have single thread of execution |
2,883 | discussion of flow controlwhen you imagined the execution of program as placing your finger on line of code in your program and moving to the next line or wherever it was sent by flow control statement singlethreaded program has only one finger but multithreaded program has multiple fingers each finger still moves to the next line of code as defined by the flow control statementsbut the fingers can be at different places in the programexecuting different lines of code at the same time (all of the programs in this book so far have been single threaded rather than having all of your code wait until the time sleep(function finishesyou can execute the delayed or scheduled code in separate thread using python' threading module the separate thread will pause for the time sleep calls meanwhileyour program can do other work in the original thread to make separate threadyou first need to make thread object by calling the threading thread(function enter the following code in new file and save it as threaddemo pyimport threadingtime print('start of program ' def takeanap()time sleep( print('wake up!' threadobj threading thread(target=takeanapw threadobj start(print('end of program 'at uwe define function that we want to use in new thread to create thread objectwe call threading thread(and pass it the keyword argument target=takeanap this means the function we want to call in the new thread is takeanap(notice that the keyword argument is target=takeanapnot target =takeanap(this is because you want to pass the takeanap(function itself as the argumentnot call takeanap(and pass its return value after we store the thread object created by threading thread(in threadobjwe call threadobj start( to create the new thread and start executing the target function in the new thread when this program is runthe output will look like thisstart of program end of program wake upthis can be bit confusing if print('end of program 'is the last line of the programyou might think that it should be the last thing printed the reason wake upcomes after it is that when threadobj start(is calledthe target function for threadobj is run in new thread of execution think of it as second finger appearing at the start of the takeanap(function the main keeping timescheduling tasksand launching programs |
2,884 | that has been executing the time sleep( callpauses for seconds after it wakes from its -second napit prints 'wake up!and then returns from the takeanap(function chronologically'wake up!is the last thing printed by the program normally program terminates when the last line of code in the file has run (or the sys exit(function is calledbut threaddemo py has two threads the first is the original thread that began at the start of the program and ends after print('end of program 'the second thread is created when threadobj start(is calledbegins at the start of the takeanap(functionand ends after takeanap(returns python program will not terminate until all its threads have terminated when you ran threaddemo pyeven though the original thread had terminatedthe second thread was still executing the time sleep( call passing arguments to the thread' target function if the target function you want to run in the new thread takes argumentsyou can pass the target function' arguments to threading thread(for examplesay you wanted to run this print(call in its own threadprint('cats''dogs''frogs'sep='cats dogs frogs this print(call has three regular arguments'cats''dogs'and 'frogs'and one keyword argumentsep=the regular arguments can be passed as list to the args keyword argument in threading thread(the keyword argument can be specified as dictionary to the kwargs keyword argument in threading thread(enter the following into the interactive shellimport threading threadobj threading thread(target=printargs=['cats''dogs''frogs']kwargs={'sep''}threadobj start(cats dogs frogs to make sure the arguments 'cats''dogs'and 'frogsget passed to print(in the new threadwe pass args=['cats''dogs''frogs'to threading thread(to make sure the keyword argument sep=gets passed to print(in the new threadwe pass kwargs={'sep'''to threading thread(the threadobj start(call will create new thread to call the print(functionand it will pass 'cats''dogs'and 'frogsas arguments and for the sep keyword argument this is an incorrect way to create the new thread that calls print()threadobj threading thread(target=print('cats''dogs''frogs'sep=') |
2,885 | return value (print()' return value is always noneas the target keyword argument it doesn' pass the print(function itself when passing arguments to function in new threaduse the threading thread(function' args and kwargs keyword arguments concurrency issues you can easily create several new threads and have them all running at the same time but multiple threads can also cause problems called concurrency issues these issues happen when threads read and write variables at the same timecausing the threads to trip over each other concurrency issues can be hard to reproduce consistentlymaking them hard to debug multithreaded programming is its own wide subject and beyond the scope of this book what you have to keep in mind is thisto avoid concurrency issuesnever let multiple threads read or write the same variables when you create new thread objectmake sure its target function uses only local variables in that function this will avoid hard-to-debug concurrency issues in your programs note beginner' tutorial on multithreaded programming is available at nostarch com/automatestuff projectmultithreaded xkcd downloader in you wrote program that downloaded all of the xkcd comic strips from the xkcd website this was single-threaded programit downloaded one comic at time much of the program' running time was spent establishing the network connection to begin the download and writing the downloaded images to the hard drive if you have broadband internet connectionyour single-threaded program wasn' fully utilizing the available bandwidth multithreaded program that has some threads downloading comics while others are establishing connections and writing the comic image files to disk uses your internet connection more efficiently and downloads the collection of comics more quickly open new file editor tab and save it as threadeddownloadxkcd py you will modify this program to add multithreading the completely modified source code is available to download from step modify the program to use function this program will mostly be the same downloading code from so 'll skip the explanation for the requests and beautiful soup code the main changes you need to make are importing the threading module and making downloadxkcd(functionwhich takes starting and ending comic numbers as parameters keeping timescheduling tasksand launching programs |
2,886 | com/ /thread that you create will call downloadxkcd(and pass different range of comics to download add the following code to your threadeddownloadxkcd py program#python threadeddownloadxkcd py downloads xkcd comics using multiple threads import requestsosbs threading os makedirs('xkcd'exist_ok=truestore comics in /xkcd def downloadxkcd(startcomicendcomic) for urlnumber in range(startcomicendcomic)download the page print('downloading page res requests get('res raise_for_status( soup bs beautifulsoup(res text'html parser'find the url of the comic image comicelem soup select('#comic img'if comicelem =[]print('could not find comic image 'elsecomicurl comicelem[ get('src'download the image print('downloading image % (comicurl)res requests get('https:comicurlres raise_for_status(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(todocreate and start the thread objects todowait for all threads to end after importing the modules we needwe make directory to store comics in and start defining downloadxkcd( we loop through all the numbers in the specified range and download each page we use beautiful soup to look through the html of each page and find the comic image if no comic image is found on pagewe print message otherwisewe get the url of the image and download the image finallywe save the image to the directory we created |
2,887 | now that we've defined downloadxkcd()we'll create the multiple threads that each call downloadxkcd(to download different ranges of comics from the xkcd website add the following code to threadeddownloadxkcd py after the downloadxkcd(function definition#python threadeddownloadxkcd py downloads xkcd comics using multiple threads --snip-create and start the thread objects downloadthreads [ list of all the thread objects for in range( )loops timescreates threads start end if start = start there is no comic so set it to downloadthread threading thread(target=downloadxkcdargs=(startend)downloadthreads append(downloadthreaddownloadthread start(first we make an empy list downloadthreadsthe list will help us keep track of the many thread objects we'll create then we start our for loop each time through the loopwe create thread object with threading thread()append the thread object to the listand call start(to start running downloadxkcd(in the new thread since the for loop sets the variable from to at steps of will be set to on the first iteration on the second iteration on the thirdand so on since we pass args=(startendto threading thread()the two arguments passed to downloadxkcd(will be and on the first iteration and on the second iteration and on the thirdand so on as the thread object' start(method is called and the new thread begins to run the code inside downloadxkcd()the main thread will continue to the next iteration of the for loop and create the next thread step wait for all threads to end the main thread moves on as normal while the other threads we create download comics but say there' some code you don' want to run in the main thread until all the threads have completed calling thread object' join(method will block until that thread has finished by using for loop to iterate over all the thread objects in the downloadthreads listthe main thread can call the join(method on each of the other threads add the following to the bottom of your program#python threadeddownloadxkcd py downloads xkcd comics using multiple threads keeping timescheduling tasksand launching programs |
2,888 | for downloadthread in downloadthreadsdownloadthread join(print('done 'the 'done string will not be printed until all of the join(calls have returned if thread object has already completed when its join(method is calledthen the method will simply return immediately if you wanted to extend this program with code that runs only after all of the comics downloadedyou could replace the print('done 'line with your new code launching other programs from python your python program can start other programs on your computer with the popen(function in the built-in subprocess module (the in the name of the popen(function stands for process if you have multiple instances of an application openeach of those instances is separate process of the same program for exampleif you open multiple windows of your web browser at the same timeeach of those windows is different process of the web browser program see figure - for an example of multiple calculator processes open at once figure - six running processes of the same calculator program every process can have multiple threads unlike threadsa process cannot directly read and write another process' variables if you think of multithreaded program as having multiple fingers following source codethen having multiple processes of the same program open is like having friend with separate copy of the program' source code you are both independently executing the same program |
2,889 | the program' filename to subprocess popen((on windowsright-click the application' start menu item and select properties to view the application' filename on macosctrl-click the application and select show package contents to find the path to the executable file the popen(function will then immediately return keep in mind that the launched program is not run in the same thread as your python program on windows computerenter the following into the interactive shellimport subprocess subprocess popen(' :\\windows\\system \\calc exe'on ubuntu linuxyou would enter the followingimport subprocess subprocess popen('/snap/bin/gnome-calculator'on macosthe process is slightly different see "opening files with default applicationson page the return value is popen objectwhich has two useful methodspoll(and wait(you can think of the poll(method as asking your driver "are we there yet?over and over until you arrive the poll(method will return none if the process is still running at the time poll(is called if the program has terminatedit will return the process' integer exit code an exit code is used to indicate whether the process terminated without errors (an exit code of or whether an error caused the process to terminate ( nonzero exit code--generally but it may vary depending on the programthe wait(method is like waiting until the driver has arrived at your destination the wait(method will block until the launched process has terminated this is helpful if you want your program to pause until the user finishes with the other program the return value of wait(is the process' integer exit code on windowsenter the following into the interactive shell note that the wait(call will block until you quit the launched ms paint program import subprocess paintproc subprocess popen(' :\\windows\\system \\mspaint exe' paintproc poll(=none true paintproc wait(doesn' return until ms paint closes paintproc poll( keeping timescheduling tasksand launching programs |
2,890 | check whether poll(returns none it shouldas the process is still running then we close the ms paint program and call wait(on the terminated process now wait(and poll()return indicating that the process terminated without errors note unlike mspaint exeif you run calc exe on windows using subprocess popen()you'll notice that wait(instantly returns even though the calculator app is still running this is because calc exe launches the calculator app and then instantly closes itself windowscalculator program is "trusted microsoft store app,and its specifics are beyond the scope of this book suffice it to sayprograms can run in many applicationand operating system-specific ways passing command line arguments to the popen(function you can pass command line arguments to processes you create with popen(to do soyou pass list as the sole argument to popen(the first string in this list will be the executable filename of the program you want to launchall the subsequent strings will be the command line arguments to pass to the program when it starts in effectthis list will be the value of sys argv for the launched program most applications with graphical user interface (guidon' use command line arguments as extensively as command line-based or terminalbased programs do but most gui applications will accept single argument for file that the applications will immediately open when they start for exampleif you're using windowscreate simple text file called :\users \al\hello txt and then enter the following into the interactive shellsubprocess popen([' :\\windows\\notepad exe'' :\\users\al\\hello txt']this will not only launch the notepad application but also have it immediately open the :\users\al\hello txt file task schedulerlaunchdand cron if you are computer savvyyou may know about task scheduler on windowslaunchd on macosor the cron scheduler on linux these well-documented and reliable tools all allow you to schedule applications to launch at specific times if you' like to learn more about themyou can find links to tutorials at using your operating system' built-in scheduler saves you from writing your own clock-checking code to schedule your programs howeveruse the time sleep(function if you just need your program to pause briefly or instead of using the operating system' scheduleryour code can loop until certain date and timecalling time sleep( each time through the loop |
2,891 | the webbrowser open(function can launch web browser from your program to specific websiterather than opening the browser application with subprocess popen(see "projectmapit py with the webbrowser moduleon page for more details running other python scripts you can launch python script from python just like any other application simply pass the python exe executable to popen(and the filename of the py script you want to run as its argument for examplethe following would run the hello py script from subprocess popen([' :\\users\\\\appdata\\local\\programs\python\\python \\python exe''hello py']pass popen( list containing string of the python executable' path and string of the script' filename if the script you're launching needs command line argumentsadd them to the list after the script' filename the location of the python executable on windows is :\users\<your username>\appdata\local\programs\python\python \python exe on macosit is /library/frameworks/python framework/versions/ /bin/python on linuxit is /usr/bin/python unlike importing the python program as modulewhen your python program launches another python programthe two are run in separate processes and will not be able to share each other' variables opening files with default applications double-clicking txt file on your computer will automatically launch the application associated with the txt file extension your computer will have several of these file extension associations set up already python can also open files this way with popen(each operating system has program that performs the equivalent of double-clicking document file to open it on windowsthis is the start program on macosthis is the open program on ubuntu linuxthis is the see program enter the following into the interactive shellpassing 'start''open'or 'seeto popen(depending on your systemfileobj open('hello txt'' 'fileobj write('helloworld!' fileobj close(import subprocess subprocess popen(['start''hello txt']shell=truekeeping timescheduling tasksand launching programs |
2,892 | passing it list containing the program name (in this example'startfor windowsand the filename we also pass the shell=true keyword argumentwhich is needed only on windows the operating system knows all of the file associations and can figure out that it should launchsaynotepad exe to handle the hello txt file on macosthe open program is used for opening both document files and programs enter the following into the interactive shell if you have macsubprocess popen(['open''/applications/calculator app/']the calculator app should open projectsimple countdown program just like it' hard to find simple stopwatch applicationit can be hard to find simple countdown application let' write countdown program that plays an alarm at the end of the countdown at high levelhere' what your program will do count down from play sound file (alarm wavwhen the countdown reaches zero this means your code will need to do the following pause for second in between displaying each number in the countdown by calling time sleep(call subprocess popen(to open the sound file with the default application open new file editor tab and save it as countdown py step count down this program will require the time module for the time sleep(function and the subprocess module for the subprocess popen(function enter the following code and save the file as countdown py#python countdown py simple countdown script import timesubprocess timeleft while timeleft print(timeleftend='' time sleep( |
2,893 | todoat the end of the countdownplay sound file after importing time and subprocessmake variable called timeleft to hold the number of seconds left in the countdown it can start at --or you can change the value here to whatever you needor even have it get set from command line argument in while loopyou display the remaining count vpause for second wand then decrement the timeleft variable before the loop starts over again the loop will keep looping as long as timeleft is greater than after thatthe countdown will be over step play the sound file while there are third-party modules to play sound files of various formatsthe quick and easy way is to just launch whatever application the user already uses to play sound files the operating system will figure out from the wav file extension which application it should launch to play the file this wav file could easily be some other sound file formatsuch as mp or ogg you can use any sound file that is on your computer to play at the end of the countdownor you can download alarm wav from /automatestuff add the following to your code#python countdown py simple countdown script import timesubprocess --snip-at the end of the countdownplay sound file subprocess popen(['start''alarm wav']shell=trueafter the while loop finishesalarm wav (or the sound file you choosewill play to notify the user that the countdown is over on windowsbe sure to include 'startin the list you pass to popen(and pass the keyword argument shell=true on macospass 'openinstead of 'startand remove shell=true instead of playing sound fileyou could save text file somewhere with message like break time is overand use popen(to open it at the end of the countdown this will effectively create pop-up window with message or you could use the webbrowser open(function to open specific website at the end of the countdown unlike some free countdown application you' find onlineyour own countdown program' alarm can be anything you wantkeeping timescheduling tasksand launching programs |
2,894 | countdown is simple delay before continuing the program' execution this can also be used for other applications and featuressuch as the followinguse time sleep(to give the user chance to press ctrl- to cancel an actionsuch as deleting files your program can print "press ctrl- to cancelmessage and then handle any keyboardinterrupt exceptions with try and except statements for long-term countdownyou can use timedelta objects to measure the number of dayshoursminutesand seconds until some point ( birthdayan anniversary?in the future summary the unix epoch (january at midnightutcis standard reference time for many programming languagesincluding python while the time time(function module returns an epoch timestamp (that isa float value of the number of seconds since the unix epoch)the datetime module is better for performing date arithmetic and formatting or parsing strings with date information the time sleep(function will block (that isnot returnfor certain number of seconds it can be used to add pauses to your program but if you want to schedule your programs to start at certain timethe instructions at the threading module is used to create multiple threadswhich is useful when you need to download multiple files or do other tasks simultaneously but make sure the thread reads and writes only local variablesor you might run into concurrency issues finallyyour python programs can launch other applications with the subprocess popen(function command line arguments can be passed to the popen(call to open specific documents with the application alternativelyyou can use the startopenor see program with popen(to use your computer' file associations to automatically figure out which application to use to open document by using the other applications on your computeryour python programs can leverage their capabilities for your automation needs practice questions what is the unix epochwhat function returns the number of seconds since the unix epochhow can you pause your program for exactly seconds |
2,895 | what does the round(function returnwhat is the difference between datetime object and timedelta objectusing the datetime modulewhat day of the week was january say you have function named spam(how can you call this function and run the code inside it in separate threadwhat should you do to avoid concurrency issues with multiple threadspractice projects for practicewrite programs that do the following prettified stopwatch expand the stopwatch project from this so that it uses the rjust(and ljust(string methods to "prettifythe output (these methods were covered in instead of output such as thislap # ( lap # ( lap # ( lap # ( the output will look like thislap lap lap lap note that you will need string versions of the lapnumlaptimeand totaltime integer and float variables in order to call the string methods on them nextuse the pyperclip module introduced in to copy the text output to the clipboard so the user can quickly paste the output to text file or email scheduled web comic downloader write program that checks the websites of several web comics and automatically downloads the images if the comic was updated since the program' last visit your operating system' scheduler (scheduled tasks on windowslaunchd on macosand cron on linuxcan run your python program once day the python program itself can download the comic and then copy it to your desktop so that it is easy to find this will free you from having to check the website yourself to see whether it has updated ( list of web comics is available at keeping timescheduling tasksand launching programs |
2,896 | sending email and te messages checking and replying to email is huge time sink of courseyou can' just write program to handle all your email for yousince each message requires its own response but you can still automate plenty of email-related tasks once you know how to write programs that can send and receive email for examplemaybe you have spreadsheet full of customer records and want to send each customer different form letter depending on their age and location details commercial software might not be able to do this for youfortunatelyyou can write your own program to send these emailssaving yourself lot of time copying and pasting form emails you can also write programs to send emails and sms texts to notify you of things even while you're away from your computer if you're automating task that takes couple of hours to doyou don' want to go back to your computer every few minutes to check on the program' status insteadthe program can just text your phone when it' done--freeing you to focus on more important things while you're away from your computer |
2,897 | read emails from gmail accountsas well as python module for using the standard smtp and imap email protocols warning highly recommend you set up separate email account for any scripts that send or receive emails this will prevent bugs in your programs from affecting your personal email account (by deleting emails or accidentally spamming your contactsfor exampleit' good idea to first do dry run by commenting out the code that actually sends or deletes emails and replacing it with temporary print(call this way you can test your program before running it for real sending and receiving email with the gmail api gmail owns close to third of the email client market shareand most likely you have at least one gmail email address because of additional security and anti-spam measuresit is easier to control gmail account through the ezgmail module than through smtplib and imapclientdiscussed later in this ezgmail is module wrote that works on top of the official gmail api and provides functions that make it easy to use gmail from python you can find full details on ezgmail at /ezgmailezgmail is not produced by or affiliated with googlefind the official gmail api documentation at / /referenceto install ezgmailrun pip install --user --upgrade ezgmail on windows (or use pip on macos and linuxthe --upgrade option will ensure that you install the latest version of the packagewhich is necessary for interacting with constantly changing online service like the gmail api enabling the gmail api before you write codeyou must first sign up for gmail email account at /quickstart/python/click the enable the gmail api button on that pageand fill out the form that appears after you've filled out the formthe page will present link to the credentials json filewhich you'll need to download and place in the same folder as your py file the credentials json file contains the client id and client secret informationwhich you should treat the same as your gmail password and not share with anyone else thenin the interactive shellenter the following codeimport ezgmailos os chdir( ' :\path\to\credentials_json_file'ezgmail init(make sure you set your current working directory to the same folder that credentials json is in and that you're connected to the internet the ezgmail init(function will open your browser to google sign-in page |
2,898 | isn' verified,but this is fineclick advanced and then go to quickstart (unsafe(if you write python scripts for others and don' want this warning appearing for themyou'll need to learn about google' app verification processwhich is beyond the scope of this book when the next page prompts you with "quickstart wants to access your google account,click allow and then close the browser token json file will be generated to give your python scripts access to the gmail account you entered the browser will only open to the login page if it can' find an existing token json file with credentials json and token jsonyour python scripts can send and read emails from your gmail account without requiring you to include your gmail password in your source code sending mail from gmail account once you have token json filethe ezgmail module should be able to send email with single function callimport ezgmail ezgmail send('recipient@example com''subject line''body of the email'if you want to attach files to your emailyou can provide an extra list argument to the send(functionezgmail send('recipient@example com''subject line''body of the email'['attachment jpg''attachment mp ']note that as part of its security and anti-spam featuresgmail might not send repeated emails with the exact same text (since these are likely spamor emails that contain exe or zip file attachments (since they are likely virusesyou can also supply the optional keyword arguments cc and bcc to send carbon copies and blind carbon copiesimport ezgmail ezgmail send('recipient@example com''subject line''body of the email'cc='friend@example com'bcc='otherfriend@example com,someoneelse@example com'if you need to remember which gmail address the token json file is configured foryou can examine ezgmail email_address note that this variable is populated only after ezgmail init(or any other ezgmail function is calledimport ezgmail ezgmail init(ezgmail email_address 'example@gmail combe sure to treat the token json file the same as your password if someone else obtains this filethey can access your gmail account (though they won' be able to change your gmail passwordto revoke previously issued token json filesgo to sending email and text messages |
2,899 | go through the login process again to obtain new token json file reading mail from gmail account gmail organizes emails that are replies to each other into conversation threads when you log in to gmail in your web browser or through an appyou're really looking at email threads rather than individual emails (even if the thread has only one email in itezgmail has gmailthread and gmailmessage objects to represent conversation threads and individual emailsrespectively gmailthread object has messages attribute that holds list of gmailmessage objects the unread(function returns list of gmailthread objects for all unread emailswhich can then be passed to ezgmail summary(to print summary of the conversation threads in that listimport ezgmail unreadthreads ezgmail unread(list of gmailthread objects ezgmail summary(unreadthreadsaljon do you want to watch robocop this weekenddec jon thanks for stopping me from buying bitcoin dec the summary(function is handy for displaying quick summary of the email threadsbut to access specific messages (and parts of messages)you'll want to examine the messages attribute of the gmailthread object the messages attribute contains list of the gmailmessage objects that make up the threadand these have subjectbodytimestampsenderand recipient attributes that describe the emaillen(unreadthreads str(unreadthreads[ ]"len(unreadthreads[ messages str(unreadthreads[ messages[ ]"to='jon doe timestamp=datetime datetime( subject='robocopsnippet='do you want to watch robocop this weekend?'>unreadthreads[ messages[ subject 'robocopunreadthreads[ messages[ body 'do you want to watch robocop this weekend?\ \nunreadthreads[ messages[ timestamp datetime datetime( unreadthreads[ messages[ sender 'al sweigart unreadthreads[ messages[ recipient 'jon doe |
Subsets and Splits
No community queries yet
The top public SQL queries from the community will appear here once available.