Ebook Automate the Boring Stuff with Python

505 2.3K 0
Ebook Automate the Boring Stuff with Python

Đang tải... (xem toàn văn)

Tài liệu hạn chế xem trước, để xem đầy đủ mời bạn chọn Tải xuống

Thông tin tài liệu

The information in this book is distributed on an “As Is” basis, without warranty. While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc. shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it.

LEARN PYTHON GET STUFF DONE In Automate the Boring Stuff with Python, you’ll learn how to use Python to write programs that in minutes what would take you hours to by hand— no prior programming experience required Once you’ve mastered the basics of programming, you’ll create Python programs that effortlessly perform useful and impressive feats of automation to: • Search for text in a file or across multiple files • Create, update, move, and rename files and folders • Search the Web and download online content • Update and format data in Excel spreadsheets of any size • Send reminder emails and text notifications • Fill out online forms Step-by-step instructions walk you through each program, and practice projects at the end of each chapter challenge you to improve those programs and use your newfound skills to automate similar tasks Don’t spend your time doing work a well-trained monkey could Even if you’ve never written a line of code, you can make your computer the grunt work Learn how in Automate the Boring Stuff with Python ABOUT THE AUTHOR Al Sweigart is a software developer and teaches programming to kids and adults He has written several Python books for beginners, including Hacking Secret Ciphers with Python, Invent Your Own Computer Games with Python, and Making Games with Python & Pygame • Split, merge, watermark, and encrypt PDFs COVERS PYTHON w w w.nostarch.com “ I L I E F L AT ” SFI-00000 $29.95 ($34.95 CDN) SHELVE IN: PROGRAMMING LANGUAGES/ PYTHON This book uses a durable binding that won’t snap shut SWEIGART T H E F I N E ST I N G E E K E N T E RTA I N M E N T ™ AU TOM AT E T HE BOR ING STUFF WITH PY THON If you’ve ever spent hours renaming files or updating hundreds of spreadsheet cells, you know how tedious tasks like these can be But what if you could have your computer them for you? AUTOMATE THE BORING STUFF WITH PYTHON P R A C T I C A L P R O G R A M M I N G F O R T O T A L B E G I N N E R S AL SWEIGART Automate the Boring Stuff with Python Automate the Boring Stuff with Python Practical Programming for Total Beginners b y Al S w e i g a r t San Francisco Automate the Boring Stuff with Python Copyright © 2015 by Al Sweigart All rights reserved No part of this work may be reproduced or transmitted in any form or by any means, electronic or mechanical, including photocopying, recording, or by any information storage or retrieval system, without the prior written permission of the copyright owner and the publisher Printed in USA Second printing 19 18 17 16 15   ISBN-10: 1-59327-599-4 ISBN-13: 978-1-59327-599-0 SFI-00000 Publisher: William Pollock Production Editor: Laurel Chun Cover Illustration: Josh Ellingson Interior Design: Octopod Studios Developmental Editors: Jennifer Griffith-Delgado, Greg Poulos, and Leslie Shen Technical Reviewer: Ari Lacenski Copyeditor: Kim Wimpsett Compositor: Susan Glinert Stevens Proofreader: Lisa Devoto Farrell Indexer: BIM Indexing and Proofreading Services For information on distribution, translations, or bulk sales, please contact No Starch Press, Inc directly: No Starch Press, Inc 245 8th Street, San Francisco, CA 94103 phone: 415.863.9900; info@nostarch.com www.nostarch.com Library of Congress Control Number: 2014953114 No Starch Press and the No Starch Press logo are registered trademarks of No Starch Press, Inc Other product and company names mentioned herein may be the trademarks of their respective owners Rather than use a trademark symbol with every occurrence of a trademarked name, we are using the names only in an editorial fashion and to the benefit of the trademark owner, with no intention of infringement of the trademark The information in this book is distributed on an “As Is” basis, without warranty While every precaution has been taken in the preparation of this work, neither the author nor No Starch Press, Inc shall have any liability to any person or entity with respect to any loss or damage caused or alleged to be caused directly or indirectly by the information contained in it This work is licensed under the Creative Commons Attribution-NonCommercial-ShareAlike 3.0 United States License To view a copy of this license, visit http://creativecommons.org/licenses/by-nc-sa/3.0/us/ or send a letter to Creative Commons, PO Box 1866, Mountain View, CA 94042, USA For my nephew Jack About the Author Al Sweigart is a software developer and tech book author living in San ­Francisco Python is his favorite programming language, and he is the developer of several open source modules for it His other books are freely available under a Creative Commons license on his website http://www inventwithpython.com/ His cat weighs 14 pounds About the Tech Reviewer Ari Lacenski is a developer of Android applications and Python software She lives in San Francisco, where she writes about Android programming at http://gradlewhy.ghost.io/ and mentors with Women Who Code She’s also a folk guitarist Brief Content s Acknowledgments xxiii Introduction Part I: Python Programming Basics 11 Chapter 1: Python Basics 13 Chapter 2: Flow Control 31 Chapter 3: Functions 61 Chapter 4: Lists 79 Chapter 5: Dictionaries and Structuring Data 105 Chapter 6: Manipulating Strings 123 Part II: Automating Tasks 145 Chapter 7: Pattern Matching with Regular Expressions 147 Chapter 8: Reading and Writing Files 173 Chapter 9: Organizing Files 197 Chapter 10: Debugging 215 Chapter 11: Web Scraping 233 Chapter 12: Working with Excel Spreadsheets 265 Chapter 13: Working with PDF and Word Documents 295 Chapter 14: Working with CSV Files and JSON Data 319 Chapter 15: Keeping Time, Scheduling Tasks, and Launching Programs 335 Chapter 16: Sending Email and Text Messages 361 Chapter 17: Manipulating Images 387 Chapter 18: Controlling the Keyboard and Mouse with GUI Automation 413 Appendix A: Installing Third-Party Modules 441 Appendix B: Running Programs 443 Appendix C: Answers to the Practice Questions 447 Index 461 Con t e n t s in De ta il Acknowledgments xxiii Introduction 1 Whom Is This Book For? Conventions What Is Programming? What Is Python? Programmers Don’t Need to Know Much Math Programming Is a Creative Activity About This Book Downloading and Installing Python Starting IDLE The Interactive Shell How to Find Help Asking Smart Programming Questions Summary 10 Part I: Python Programming Basics 11 Python Basics 13 Entering Expressions into the Interactive Shell The Integer, Floating-Point, and String Data Types String Concatenation and Replication Storing Values in Variables Assignment Statements Variable Names Your First Program Dissecting Your Program Comments The print() Function The input() Function Printing the User’s Name The len() Function The str(), int(), and float() Functions Summary Practice Questions Flow Control 14 16 17 18 18 20 21 22 23 23 23 24 24 25 28 28 31 Boolean Values 32 Comparison Operators 33 Boolean Operators 35 Binary Boolean Operators The not Operator Mixing Boolean and Comparison Operators Elements of Flow Control Conditions Blocks of Code Program Execution Flow Control Statements if Statements else Statements elif Statements while Loop Statements break Statements continue Statements for Loops and the range() Function Importing Modules from import Statements Ending a Program Early with sys.exit() Summary Practice Questions 35 36 36 37 37 37 38 38 38 39 40 45 49 50 53 57 58 58 58 59 Functions 61 def Statements with Parameters Return Values and return Statements The None Value Keyword Arguments and print() Local and Global Scope Local Variables Cannot Be Used in the Global Scope Local Scopes Cannot Use Variables in Other Local Scopes Global Variables Can Be Read from a Local Scope Local and Global Variables with the Same Name The global Statement Exception Handling A Short Program: Guess the Number Summary Practice Questions Practice Projects The Collatz Sequence Input Validation 63 63 65 65 67 67 68 69 69 70 72 74 76 76 77 77 77 Lists 79 The List Data Type Getting Individual Values in a List with Indexes Negative Indexes Getting Sublists with Slices Getting a List’s Length with len() Changing Values in a List with Indexes x   Contents in Detail 80 80 82 82 83 83 formulas, in Excel spreadsheets, 284–285 forward() method, 261 forward slash (/), 174–175 FROM search key, 370 fromtimestamp() function, 341, 346 functions See also names of individual functions arguments, 23, 63 as “black box”, 72 built-in, 57 def statements, 63 exception handling, 72–74 keyword arguments, 65–66 None value and, 65 overview, 61–62 parameters, 63 return values, 63–65 G get_active_sheet() method, 268 get_addresses() method, 374 get_attribute() method, 258 getcolor() function, 388–389, 393 get_column_letter() function, 270 getcwd() function, 175 get() function overview, 109 requests module, 237 get_highest_column() method, 269, 377 get_highest_row() method, 269 get_payload() method, 374–375 getpixel() function, 400, 423, 424 get_sheet_by_name() method, 268 get_sheet_names() method, 268 getsize() function, 179 get_subject() method, 374 getText() function, 308–309 GIF format, 392 global scope, 70–71 Gmail, 363, 365, 367 gmail_search() method, 372 Google Maps, 234–236 graphical user interface automation See GUI (graphical user interface) automation greater than (>) operator, 33 greater than or equal to (>=) operator, 33 greedy matching dot-star for, 161 in regular expressions, 156–157 group() method, 151, 152–153 groups, regular expression matching greedy, 156–157 nongreedy, 157 one or more, 155–156 optional, 154–155 specific reptitions, 156 zero or more, 155 using parentheses, 152–153 using pipe character in, 153–154 Guess the Number program, 74–76 GUI (graphical user interface) automation See also form filler project controlling keyboard, 426–429 hotkey combinations, 429 key names, 427–428 pressing and releasing, 428–429 sending string from keyboard, 426–427 controlling mouse, 415–417, 419–423 clicking mouse, 420 dragging mouse, 420–422 scrolling mouse, 422–423 determining mouse position, 417–419 image recognition, 425–426 installing pyautogui module, 414 logging out of program, 414 overview, 413–414 screenshots, 423–424 stopping program, 414–415 H %H directive, 344 hash character (#), 126 headings, Word document, 314–315 help asking online, 9–10 for error messages, 8–9 hotkey combinations, 429 hotkey() function, 429, 430 Hotmail.com, 363, 367 HTML (Hypertext Markup Language) browser developer tools and, 242–243 finding elements, 244 learning resources, 240 overview, 240–241 viewing page source, 241–242 Index   467 I %I directive, 344 id attribute, 241 IDLE (interactive development environment) creating programs, 21–22 debugging in overview, 225–227 stepping through program, 227–229 using breakpoints, 229–231 expressions in, 14–16 overview, running scripts outside of, 136 starting, 7–8 if statements overview, 38–39 using in while loop, 46–47 imageDraw module, 406 imageDraw objects, 406–408 ImageFont objects, 408–410 Image objects, 391–399 images adding logo to, 401–405 attributes for, 392–393 box tuples, 390 color values in, 388–389 coordinates in, 389–390 copying and pasting in, 394–396 cropping, 393–394 drawing on example program, 407–408 ellipses, 407 ImageDraw module, 406 lines, 406–407 points, 406 polygons, 407 rectangles, 407 text, 408–410 flipping, 398–399 opening with Pillow, 390–391 pixel manipulation, 400 recognition of, 425–426 resizing, 397 RGBA values, 388–389 rotating, 398–399 transparent pixels, 397 IMAP (Internet Message Access Protocol) defined, 366 deleting messages, 375 468   Index disconnecting from server, 375–376 fetching messages, 372–375 folders, 368–369 logging into server, 368 searching messages, 368–371 imapclient module, 366 IMAPClient objects, 367–368 immutable data types, 94–96 importing modules overview, 57–58 pyautogui module, 417 imprint attribute, 311 im variable, 423 indentation, 93 indexes for dictionaries See keys, dictionary for lists changing values using, 83 getting value using, 80–81 negative, 82 removing values from list using, 84 for strings, 126–127 IndexError, 106 index() method, 89 infinite loops, 49, 51, 418 INFO level, 223 in operator using with dictionaries, 109 using with lists, 87 using with strings, 127 input() function overview, 23–24, 89–90 using for sensitive information, 365 installing openpyxl module, 266 pyautogui module, 414 Python, 6–7 selenium module, 256 third-party modules, 441–442 int, 17 See also integers integer division/floored quotient (//) operator, 15 integers floating-point equivalence, 27 overview, 17 interactive development environment See IDLE (interactive development environment) interactive shell See IDLE Internet Explorer, developer tools in, 242–243 Internet Message Access Protocol See IMAP (Internet Message Access Protocol) interpreter, Python, int() function, 25–28 isabs() function, 177 isalnum() method, 129–131 isalpha() method, 129–130 isdecimal() method, 129–131 isdir() function, 180 is_displayed() method, 258 is_enabled() method, 258 isfile() function, 180 islower() method, 128–129 is_selected() method, 258 isspace() method, 130 istitle() method, 130 isupper() method, 128–129 italic attribute, 311 items() method, 107–108 iter_content() method, 239–240 J %j directive, 344 join() method, 131–132, 174–175, 177, 352 JPEG format, 392 JSON files APIs for, 327–328 defined, 319–320 format overview, 327–328 reading, 328–329 and weather data project, 329–332 writing, 329 justifying text, 133–134 K keyboard controlling, with PyAutoGUI hotkey combinations, 429 pressing and releasing keys, 428–429 sending string from keyboard, 426–427 key names, 427–428 KeyboardInterrupt exception, 340, 417, 418 keyDown() function, 428, 429, 430 keys, dictionary, 105 keys() method, 107–108 keyUp() function, 428, 429, 430 keyword arguments, 65–66 L LARGER search key, 370 launchd, 354–355 launching programs and countdown project, 357–358 opening files with default applications, 355–356 opening websites, 355 overview, 352–354 passing command line arguments to processes, 354 poll() method, 353 running Python scripts, 355 scheduling, 354–355 sleep() function, 355 wait() method, 354 len() function, 307–308 finding number of values in list, 83 overview, 24–25 less than (

Ngày đăng: 15/05/2017, 11:20

Từ khóa liên quan

Mục lục

  • About the Author

  • Brief Contents

  • Contents in Detail

  • Acknowledgments

  • Introduction

    • Whom Is This Book For?

    • Conventions

    • What Is Programming?

      • What Is Python?

      • Programmers Don’t Need to Know Much Math

      • Programming Is a Creative Activity

    • About This Book

    • Downloading and Installing Python

    • Starting IDLE

      • The Interactive Shell

    • How to Find Help

    • Asking Smart Programming Questions

    • Summary

  • Part I: Python Programming Basics

    • Chapter 1: Python Basics

      • Entering Expressions into the Interactive Shell

      • The Integer, Floating-Point, and String Data Types

      • String Concatenation and Replication

      • Storing Values in Variables

        • Assignment Statements

        • Variable Names

      • Your First Program

      • Dissecting Your Program

        • Comments

        • The print() Function

        • The input() Function

        • Printing the User’s Name

        • The len() Function

        • The str(), int(), and float() Functions

      • Summary

      • Practice Questions

    • Chapter 2: Flow Control

      • Boolean Values

      • Comparison Operators

      • Boolean Operators

        • Binary Boolean Operators

        • The not Operator

      • Mixing Boolean and Comparison Operators

      • Elements of Flow Control

        • Conditions

        • Blocks of Code

      • Program Execution

      • Flow Control Statements

        • if Statements

        • else Statements

        • elif Statements

        • while Loop Statements

        • break Statements

        • continue Statements

        • for Loops and the range() Function

      • Importing Modules

        • from import Statements

      • Ending a Program Early with sys.exit()

      • Summary

      • Practice Questions

    • Chapter 3: Functions

      • def Statements with Parameters

      • Return Values and return Statements

      • The None Value

      • Keyword Arguments and print()

      • Local and Global Scope

        • Local Variables Cannot Be Used in the Global Scope

        • Local Scopes Cannot Use Variables in Other Local Scopes

        • Global Variables Can Be Read from a Local Scope

        • Local and Global Variables with the Same Name

      • The global Statement

      • Exception Handling

      • A Short Program: Guess the Number

      • Summary

      • Practice Questions

      • Practice Projects

        • The Collatz Sequence

        • Input Validation

    • Chapter 4: Lists

      • The List Data Type

        • Getting Individual Values in a List with Indexes

        • Negative Indexes

        • Getting Sublists with Slices

        • Getting a List’s Length with len()

        • Changing Values in a List with Indexes

        • List Concatenation and List Replication

        • Removing Values from Lists with del Statements

      • Working with Lists

        • Using for Loops with Lists

        • The in and not in Operators

        • The Multiple Assignment Trick

      • Augmented Assignment Operators

      • Methods

        • Finding a Value in a List with the index() Method

        • Adding Values to Lists with the append() and insert() Methods

        • Removing Values from Lists with remove()

        • Sorting the Values in a List with the sort() Method

      • Example Program: Magic 8 Ball with a List

      • List-like Types: Strings and Tuples

        • Mutable and Immutable Data Types

        • The Tuple Data Type

        • Converting Types with the list() and tuple() Functions

      • References

        • Passing References

        • The copy Module’s copy() and deepcopy() Functions

      • Summary

      • Practice Questions

      • Practice Projects

        • Comma Code

        • Character Picture Grid

    • Chapter 5: Dictionaries and Structuring Data

      • The Dictionary Data Type

        • Dictionaries vs. Lists

        • The keys(), values(), and items() Methods

        • Checking Whether a Key or Value Exists in a Dictionary

        • The get() Method

        • The setdefault() Method

      • Pretty Printing

      • Using Data Structures to Model Real-World Things

        • A Tic-Tac-Toe Board

        • Nested Dictionaries and Lists

      • Summary

      • Practice Questions

      • Practice Projects

        • Fantasy Game Inventory

        • List to Dictionary Function for Fantasy Game Inventory

    • Chapter 6: Manipulating Strings

      • Working with Strings

        • String Literals

        • Indexing and Slicing Strings

        • The in and not in Operators with Strings

      • Useful String Methods

        • The upper(), lower(), isupper(), and islower() String Methods

        • The isX String Methods

        • The startswith() and endswith() String Methods

        • The join() and split() String Methods

        • Justifying Text with rjust(), ljust(), and center()

        • Removing Whitespace with strip(), rstrip(), and lstrip()

        • Copying and Pasting Strings with the pyperclip Module

      • Project: Password Locker

        • Step 1: Program Design and Data Structures

        • Step 2: Handle Command-Line Arguments

        • Step 3: Copy the Right Password

      • Project: Adding Bullets to Wiki Markup

        • Step 1: Copy and Paste from the Clipboard

        • Step 2: Separate the Lines of Text and Add the Star

        • Step 3: Join the Modified Lines

      • Summary

      • Practice Questions

      • Practice Projects

        • Table Printer

  • Part II: Automating Tasks

    • Chapter 7: Pattern Matching with Regular Expressions

      • Finding Patterns of Text Without Regular Expressions

      • Finding Patterns of Text with Regular Expressions

        • Creating Regex Objects

        • Matching Regex Objects

        • Review of Regular Expression Matching

      • More Pattern Matching with Regular Expressions

        • Grouping with Parentheses

        • Matching Multiple Groups with the Pipe

        • Optional Matching with the Question Mark

        • Matching Zero or More with the Star

        • Matching One or More with the Plus

        • Matching Specific Repetitions with Curly Braces

      • Greedy and Nongreedy Matching

      • The findall() Method

      • Character Classes

      • Making Your Own Character Classes

      • The Caret and Dollar Sign Characters

      • The Wildcard Character

        • Matching Everything with Dot-Star

        • Matching Newlines with the Dot Character

      • Review of Regex Symbols

      • Case-Insensitive Matching

      • Substituting Strings with the sub() Method

      • Managing Complex Regexes

      • Combining re.IGNORECASE, re.DOTALL, and re.VERBOSE

      • Project: Phone Number and Email Address Extractor

        • Step 1: Create a Regex for Phone Numbers

        • Step 2: Create a Regex for Email Addresses

        • Step 3: Find All Matches in the Clipboard Text

        • Step 4: Join the Matches into a String for the Clipboard

        • Running the Program

        • Ideas for Similar Programs

      • Summary

      • Practice Questions

      • Practice Projects

        • Strong Password Detection

        • Regex Version of strip()

    • Chapter 8: Reading and Writing Files

      • Files and File Paths

        • Backslash on Windows and Forward Slash on OS X and Linux

        • The Current Working Directory

        • Absolute vs. Relative Paths

        • Creating New Folders with os.makedirs()

      • The os.path Module

        • Handling Absolute and Relative Paths

        • Finding File Sizes and Folder Contents

        • Checking Path Validity

      • The File Reading/Writing Process

        • Opening Files with the open() Function

        • Reading the Contents of Files

        • Writing to Files

      • Saving Variables with the shelve Module

      • Saving Variables with the pprint.pformat() Function

      • Project: Generating Random Quiz Files

        • Step 1: Store the Quiz Data in a Dictionary

        • Step 2: Create the Quiz File and Shuffle the Question Order

        • Step 3: Create the Answer Options

        • Step 4: Write Content to the Quiz and Answer Key Files

      • Project: Multiclipboard

        • Step 1: Comments and Shelf Setup

        • Step 2: Save Clipboard Content with a Keyword

        • Step 3: List Keywords and Load a Keyword’s Content

      • Summary

      • Practice Questions

      • Practice Projects

        • Extending the Multiclipboard

        • Mad Libs

        • Regex Search

    • Chapter 9: Organizing Files

      • The shutil Module

        • Copying Files and Folders

        • Moving and Renaming Files and Folders

        • Permanently Deleting Files and Folders

        • Safe Deletes with the send2trash Module

      • Walking a Directory Tree

      • Compressing Files with the zipfile Module

        • Reading ZIP Files

        • Extracting from ZIP Files

        • Creating and Adding to ZIP Files

      • Project: Renaming Files with American-Style Dates to European-Style Dates

        • Step 1: Create a Regex for American-Style Dates

        • Step 2: Identify the Date Parts from the Filenames

        • Step 3: Form the New Filename and Rename the Files

        • Ideas for Similar Programs

      • Project: Backing Up a Folder into a ZIP File

        • Step 1: Figure Out the ZIP File’s Name

        • Step 2: Create the New ZIP File

        • Step 3: Walk the Directory Tree and Add to the ZIP File

        • Ideas for Similar Programs

      • Summary

      • Practice Questions

      • Practice Projects

        • Selective Copy

        • Deleting Unneeded Files

        • Filling in the Gaps

    • Chapter 10: Debugging

      • Raising Exceptions

      • Getting the Traceback as a String

      • Assertions

        • Using an Assertion in a Traffic Light Simulation

        • Disabling Assertions

      • Logging

        • Using the logging Module

        • Don’t Debug with print()

        • Logging Levels

        • Disabling Logging

        • Logging to a File

      • IDLE’s Debugger

        • Go

        • Step

        • Over

        • Out

        • Quit

        • Debugging a Number Adding Program

        • Breakpoints

      • Summary

      • Practice Questions

      • Practice Projects

        • Debugging Coin Toss

    • Chapter 11: Web Scraping

      • Project: mapIt.py with the webbrowser Module

        • Step 1: Figure Out the URL

        • Step 2: Handle the Command-Line Arguments

        • Step 3: Handle the Clipboard Content and Launch the Browser

        • Ideas for Similar Programs

      • Downloading Files from the Web with the requests Module

        • Downloading a Web Page with the requests.get() Function

        • Checking for Errors

      • Saving Downloaded Files to the Hard Drive

      • HTML

        • Resources for Learning HTML

        • A Quick Refresher

        • Viewing the Source HTML of a Web Page

        • Opening Your Browser’s Developer Tools

        • Using the Developer Tools to Find HTML Elements

      • Parsing HTML with the BeautifulSoup Module

        • Creating a Soup Object from HTML

        • Finding an Element with the select() Method

        • Getting Data from an Element’s Attributes

      • Project: “I’m Feeling Lucky” Google Search

        • Step 1: Get the Command-Line Arguments and Request the Search Page

        • Step 2: Find All the Results

        • Step 3: Open Web Browsers for Each Result

        • Ideas for Similar Programs

      • Project: Downloading All XKCD Comics

        • Step 1: Design the Program

        • Step 2: Download the Web Page

        • Step 3: Find and Download the Comic Image

        • Step 4: Save the Image and Find the Previous Comic

        • Ideas for Similar Programs

      • Controlling the Browser with the selenium Module

        • Starting a Selenium-Controlled Browser

        • Finding Elements on the Page

        • Clicking the Page

        • Filling Out and Submitting Forms

        • Sending Special Keys

        • Clicking Browser Buttons

        • More Information on Selenium

      • Summary

      • Practice Questions

      • Practice Projects

        • Command-Line Emailer

        • Image Site Downloader

        • 2048

        • Link Verification

    • Chapter 12: Working with Excel Spreadsheets

      • Excel Documents

      • Installing the openpyxl Module

      • Reading Excel Documents

        • Opening Excel Documents with OpenPyXL

        • Getting Sheets from the Workbook

        • Getting Cells from the Sheets

        • Converting Between Column Letters and Numbers

        • Getting Rows and Columns from the Sheets

        • Workbooks, Sheets, Cells

      • Project: Reading Data from a Spreadsheet

        • Step 1: Read the Spreadsheet Data

        • Step 2: Populate the Data Structure

        • Step 3: Write the Results to a File

        • Ideas for Similar Programs

      • Writing Excel Documents

        • Creating and Saving Excel Documents

        • Creating and Removing Sheets

        • Writing Values to Cells

      • Project: Updating a Spreadsheet

        • Step 1: Set Up a Data Structure with the Update Information

        • Step 2: Check All Rows and Update Incorrect Prices

        • Ideas for Similar Programs

      • Setting the Font Style of Cells

      • Font Objects

      • Formulas

      • Adjusting Rows and Columns

        • Setting Row Height and Column Width

        • Merging and Unmerging Cells

        • Freeze Panes

      • Charts

      • Summary

      • Practice Questions

      • Practice Projects

        • Multiplication Table Maker

        • Blank Row Inserter

        • Spreadsheet Cell Inverter

        • Text Files to Spreadsheet

        • Spreadsheet to Text Files

    • Chapter 13: Working with PDF and Word Documents

      • PDF Documents

        • Extracting Text from PDFs

        • Decrypting PDFs

        • Creating PDFs

      • Project: Combining Select Pages from Many PDFs

        • Step 1: Find All PDF Files

        • Step 2: Open Each PDF

        • Step 3: Add Each Page

        • Step 4: Save the Results

        • Ideas for Similar Programs

      • Word Documents

        • Reading Word Documents

        • Getting the Full Text from a .docx File

        • Styling Paragraph and Run Objects

        • Creating Word Documents with Nondefault Styles

        • Run Attributes

        • Writing Word Documents

        • Adding Headings

        • Adding Line and Page Breaks

        • Adding Pictures

      • Summary

      • Practice Questions

      • Practice Projects

        • PDF Paranoia

        • Custom Invitations as Word Documents

        • Brute-Force PDF Password Breaker

    • Chapter 14: Working with CSV Files and JSON Data

      • The csv Module

        • Reader Objects

        • Reading Data from Reader Objects in a for Loop

        • Writer Objects

        • The delimiter and lineterminator Keyword Arguments

      • Project: Removing the Header from CSV Files

        • Step 1: Loop Through Each CSV File

        • Step 2: Read in the CSV File

        • Step 3: Write Out the CSV File Without the First Row

        • Ideas for Similar Programs

      • JSON and APIs

      • The json Module

        • Reading JSON with the loads() Function

        • Writing JSON with the dumps() Function

      • Project: Fetching Current Weather Data

        • Step 1: Get Location from the Command Line Argument

        • Step 2: Download the JSON Data

        • Step 3: Load JSON Data and Print Weather

        • Ideas for Similar Programs

      • Summary

      • Practice Questions

      • Practice Project

        • Excel-to-CSV Converter

    • Chapter 15: Keeping Time, Scheduling Tasks, and Launching Programs

      • The time Module

        • The time.time() Function

        • The time.sleep() Function

      • Rounding Numbers

      • Project: Super Stopwatch

        • Step 1: Set Up the Program to Track Times

        • Step 2: Track and Print Lap Times

        • Ideas for Similar Programs

      • The datetime Module

        • The Timedelta Data Type

        • Pausing Until a Specific Date

        • Converting Datetime Objects into Strings

        • Converting Strings into Datetime Objects

      • Review of Python’s Time Functions

      • Multithreading

        • Passing Arguments to the Thread’s Target Function

        • Concurrency Issues

      • Project: Multithreaded XKCD Downloader

        • Step 1: Modify the Program to Use a Function

        • Step 2: Create and Start Threads

        • Step 3: Wait for All Threads to End

      • Launching Other Programs from Python

        • Passing Command Line Arguments to Popen()

        • Task Scheduler, launchd, and cron

        • Opening Websites with Python

        • Running Other Python Scripts

        • Opening Files with Default Applications

      • Project: Simple Countdown Program

        • Step 1: Count Down

        • Step 2: Play the Sound File

        • Ideas for Similar Programs

      • Summary

      • Practice Questions

      • Practice Projects

        • Prettified Stopwatch

        • Scheduled Web Comic Downloader

    • Chapter 16: Sending Email and Text Messages

      • SMTP

      • Sending Email

        • Connecting to an SMTP Server

        • Sending the SMTP “Hello” Message

        • Starting TLS Encryption

        • Logging in to the SMTP Server

        • Sending an Email

        • Disconnecting from the SMTP Server

      • IMAP

      • Retrieving and Deleting Emails with IMAP

        • Connecting to an IMAP Server

        • Logging in to the IMAP Server

        • Searching for Email

        • Fetching an Email and Marking It As Read

        • Getting Email Addresses from a Raw Message

        • Getting the Body from a Raw Message

        • Deleting Emails

        • Disconnecting from the IMAP Server

      • Project: Sending Member Dues Reminder Emails

        • Step 1: Open the Excel File

        • Step 2: Find All Unpaid Members

        • Step 3: Send Customized Email Reminders

      • Sending Text Messages with Twilio

        • Signing Up for a Twilio Account

        • Sending Text Messages

      • Project: “Just Text Me” Module

      • Summary

      • Practice Questions

      • Practice Projects

        • Random Chore Assignment Emailer

        • Umbrella Reminder

        • Auto Unsubscriber

        • Control Your Computer Through Email

    • Chapter 17: Manipulating Images

      • Computer Image Fundamentals

        • Colors and RGBA Values

        • Coordinates and Box Tuples

      • Manipulating Images with Pillow

        • Working with the Image Data Type

        • Cropping Images

        • Copying and Pasting Images onto Other Images

        • Resizing an Image

        • Rotating and Flipping Images

        • Changing Individual Pixels

      • Project: Adding a Logo

        • Step 1: Open the Logo Image

        • Step 2: Loop Over All Files and Open Images

        • Step 3: Resize the Image

        • Step 4: Add the Logo and Save the Changes

        • Ideas for Similar Programs

      • Drawing on Images

        • Drawing Shapes

        • Drawing Text

      • Summary

      • Practice Questions

      • Practice Projects

        • Extending and Fixing the Chapter Project Programs

        • Identifying Photo Folders on the Hard Drive

        • Custom Seating Cards

    • Chapter 18: Controlling the Keyboard and Mouse with GUI Automation

      • Installing the pyautogui Module

      • Staying on Track

        • Shutting Down Everything by Logging Out

        • Pauses and Fail-Safes

      • Controlling Mouse Movement

        • Moving the Mouse

        • Getting the Mouse Position

      • Project: “Where Is the Mouse Right Now?”

        • Step 1: Import the Module

        • Step 2: Set Up the Quit Code and Infinite Loop

        • Step 3: Get and Print the Mouse Coordinates

      • Controlling Mouse Interaction

        • Clicking the Mouse

        • Dragging the Mouse

        • Scrolling the Mouse

      • Working with the Screen

        • Getting a Screenshot

        • Analyzing the Screenshot

      • Project: Extending the mouseNow Program

      • Image Recognition

      • Controlling the Keyboard

        • Sending a String from the Keyboard

        • Key Names

        • Pressing and Releasing the Keyboard

        • Hotkey Combinations

      • Review of the PyAutoGUI Functions

      • Project: Automatic Form Filler

        • Step 1: Figure Out the Steps

        • Step 2: Set Up Coordinates

        • Step 3: Start Typing Data

        • Step 4: Handle Select Lists and Radio Buttons

        • Step 5: Submit the Form and Wait

      • Summary

      • Practice Questions

      • Practice Projects

        • Looking Busy

        • Instant Messenger Bot

        • Game-Playing Bot Tutorial

  • Appendix A: Installing Third-Party Modules

    • The pip Tool

    • Installing Third-Party Modules

  • Appendix B: Running Programs

    • Shebang Line

    • Running Python Programs on Windows

    • Running Python Programs on OS X and Linux

    • Running Python Programs with Assertions Disabled

  • Appendix C: Practice Question Answers

    • Chapter 1

    • Chapter 2

    • Chapter 3

    • Chapter 4

    • Chapter 5

    • Chapter 6

    • Chapter 7

    • Chapter 8

    • Chapter 9

    • Chapter 10

    • Chapter 11

    • Chapter 12

    • Chapter 13

    • Chapter 14

    • Chapter 15

    • Chapter 16

    • Chapter 17

    • Chapter 18

  • Index

Tài liệu cùng người dùng

Tài liệu liên quan