id
int64
0
25.6k
text
stringlengths
0
4.59k
2,600
for loop can also iterate over the keys or both keys and valuesfor in spam keys()print(kcolor age for in spam items()print( ('color''red'('age' when you use the keys()values()and items(methodsa for loop can iterate over the keysvaluesor key-value pairs in dictionaryrespectively notice that the values in the dict_items ...
2,601
true 'colorin spam keys(false 'colornot in spam keys(true 'colorin spam false in the previous examplenotice that 'colorin spam is essentially shorter version of writing 'colorin spam keys(this is always the caseif you ever want to check whether value is (or isn'ta key in the dictionaryyou can simply use the in (or not ...
2,602
first argument passed to the method is the key to check forand the second argument is the value to set at that key if the key does not exist if the key does existthe setdefault(method returns the key' value enter the following into the interactive shellspam {'name''pooka''age' spam setdefault('color''black''blackspam {...
2,603
the space character appears timesand the uppercase letter appears time this program will work no matter what string is inside the message variableeven if the string is millions of characters longpretty printing if you import the pprint module into your programsyou'll have access to the pprint(and pformat(functions that...
2,604
even before the internetit was possible to play game of chess with someone on the other side of the world each player would set up chessboard at their home and then take turns mailing postcard to each other describing each move to do thisthe players needed way to unambiguously describe the state of the board and their ...
2,605
figure - chess board modeled by the dictionary {' ''bking'' ''wqueen'' ''bbishop'' ''bqueen'' ''wking'but for another exampleyou'll use game that' little simpler than chesstic-tac-toe tic-tac-toe board tic-tac-toe board looks like large hash symbol (#with nine slots that can each contain an xan oor blank to represent t...
2,606
store this board-as- -dictionary in variable named theboard open new file editor windowand enter the following source codesaving it as tictactoe pytheboard {'top- '''top- '''top- '''mid- '''mid- '''mid- '''low- '''low- '''low- ''the data structure stored in the theboard variable represents the tic-tactoe board in figur...
2,607
look like thistheboard {'top- '' ''top- '' ''top- '' ''mid- '' ''mid- '' ''mid- '''low- '''low- '''low- '' 'the data structure in theboard now represents the tic-tac-toe board in figure - figure - player wins of coursethe player sees only what is printed to the screennot the contents of variables let' create function t...
2,608
pass it try changing the code to the followingtheboard {'top- '' ''top- '' ''top- '' ''mid- '' ''mid- '' ''mid- '''low- '''low- '''low- '' 'def printboard(board)print(board['top- ''|board['top- ''|board['top- ']print('-+-+-'print(board['mid- ''|board['mid- ''|board['mid- ']print('-+-+-'print(board['low- ''|board['low- ...
2,609
print('-+-+-'print(board['low- ''|board['low- ''|board['low- ']turn 'xfor in range( )printboard(theboardprint('turn for turn move on which space?'move input(theboard[moveturn if turn =' 'turn 'oelseturn 'xprintboard(theboardyou can view the execution of this program at the new code prints out the board at the start of ...
2,610
if you are curiousthe source code for complete tic-tac-toe program is described in the resources available from nested dictionaries and lists modeling tic-tac-toe board was fairly simplethe board needed only single dictionary value with nine key-value pairs as you model more complicated thingsyou may find you need dict...
2,611
having this information in data structure along with the totalbrought(function would save you lot of timeyou can model things with data structures in whatever way you likeas long as the rest of the code in your program can work with the data model correctly when you first begin programmingdon' worry so much about the "...
2,612
for practicewrite programs to do the following tasks chess dictionary validator in this we used the dictionary value {' ''bking'' ''wqueen'' ''bbishop'' ''bqueen'' ''wking'to represent chess board write function named isvalidchessboard(that takes dictionary argument and returns true or false depending on if the board i...
2,613
imagine that vanquished dragon' loot is represented as list of strings like thisdragonloot ['gold coin''dagger''gold coin''gold coin''ruby'write function named addtoinventory(inventoryaddeditems)where the inventory parameter is dictionary representing the player' inventory (like in the previous projectand the addeditem...
2,614
nipul at ing ings text is one of the most common forms of data your programs will handle you already know how to concatenate two string values together with the operatorbut you can do much more than that you can extract partial strings from string valuesadd or remove spacingconvert letters to lowercase or uppercaseand ...
2,615
two different programming projectsa simple clipboard that stores multiple strings of text and program to automate the boring chore of formatting pieces of text working with strings let' look at some of the ways python lets you writeprintand access strings in your code string literals typing string values in python code...
2,616
escape character prints as \single quote \double quote \ tab \ newline (line break\backslash enter the following into the interactive shellprint("hello there!\nhow are you?\ni\' doing fine "hello therehow are youi' doing fine raw strings you can place an before the beginning quotation mark of string to make it raw stri...
2,617
like thisdear aliceeve' cat has been arrested for catnappingcat burglaryand extortion sincerelybob notice that the single quote character in eve' does not need to be escaped escaping single and double quotes is optional in multiline strings the following print(call would print identical text but doesn' use multiline st...
2,618
spam 'helloworld!spam[ 'hspam[ 'ospam[- '!spam[ : 'hellospam[: 'hellospam[ :'world!if you specify an indexyou'll get the character at that position in the string if you specify range from one index to anotherthe starting index is included and the ending index is not that' whyif spam is 'helloworld!'spam[ : is 'hellothe...
2,619
putting strings inside other strings putting strings inside other strings is common operation in programming so farwe've been using the operator and string concatenation to do thisname 'alage 'hellomy name is name am str(ageyears old 'hellomy name is al am years old howeverthis requires lot of tedious typing simpler ap...
2,620
the upper(and lower(string methods return new string where all the letters in the original string have been converted to uppercase or lowercaserespectively nonletter characters in the string remain unchanged enter the following into the interactive shellspam 'helloworld!spam spam upper(spam 'helloworld!spam spam lower(...
2,621
false enter the following into the interactive shelland notice what each method call returnsspam 'helloworld!spam islower(false spam isupper(false 'helloisupper(true 'abc islower(true ' islower(false ' isupper(false since the upper(and lower(string methods themselves return stringsyou can call string methods on those r...
2,622
'helloisalpha(true 'hello isalpha(false 'hello isalnum(true 'helloisalnum(true ' isdecimal(true isspace(true 'this is title caseistitle(true 'this is title case istitle(true 'this is not title caseistitle(false 'this is not title case eitheristitle(false the isx(string methods are helpful when you need to validate user...
2,623
enter your ageforty two please enter number for your age enter your age select new password (letters and numbers only)secr tpasswords can only have letters and numbers select new password (letters and numbers only)secr you can view the execution of this program at /validateinputcalling isdecimal(and isalnum(on variable...
2,624
the following into the interactive shell'join(['cats''rats''bats']'catsratsbatsjoin(['my''name''is''simon']'my name is simon'abcjoin(['my''name''is''simon']'myabcnameabcisabcsimonnotice that the string join(calls on is inserted between each string of the list argument for examplewhen join(['cats''rats''bats']is called ...
2,625
the partition(string method can split string into the text before and after separator string this method searches the string it is called on for the separator string it is passedand returns tuple of three substrings for the "before,"separator,and "aftersubstrings enter the following into the interactive shell'helloworl...
2,626
helloworld'helloljust( 'hello 'hellorjust( says that we want to right-justify 'helloin string of total length 'hellois five charactersso five spaces will be added to its leftgiving us string of characters with 'hellojustified right an optional second argument to rjust(and ljust(will specify fill character other than sp...
2,627
column of tableand rightwidth for the right column it prints titlepicnic itemscentered above the table thenit loops through the dictionaryprinting each key-value pair on line with the key justified left and padded by periodsand the value justified right and padded by spaces after defining printpicnic()we define the dic...
2,628
ampand capital from the ends of the string stored in spam the order of the characters in the string passed to strip(does not matterstrip('amps'will do the same thing as strip('maps'or strip('spam'numeric values of characters with the ord(and chr(functions computers store information as bytes--strings of binary numbersw...
2,629
so faryou've been running your python scripts using the interactive shell and file editor in mu howeveryou won' want to go through the inconvenience of opening mu and the python script each time you want to run script fortunatelythere are shortcuts you can set up to make running python scripts easier the steps are slig...
2,630
this is the first "projectof the book from here oneach will have projects that demonstrate the concepts covered in the the projects are written in style that takes you from blank file editor window to fullworking program just like with the interactive shell examplesdon' only read the project sections--follow along on y...
2,631
now that the key phrase is stored as string in the variable keyphraseyou need to see whether it exists in the text dictionary as key if soyou want to copy the key' value to the clipboard using pyperclip copy((since you're using the pyperclip moduleyou need to import it note that you don' actually need the keyphrase var...
2,632
when editing wikipedia articleyou can create bulleted list by putting each list item on its own line and placing star in front but say you have really large list that you want to add bullet points to you could just type those stars at the beginning of each lineone by one or you could automate this task with short pytho...
2,633
the program eventually the next step is to actually implement that piece of the program step separate the lines of text and add the star the call to pyperclip paste(returns all the text on the clipboard as one big string if we used the "list of lists of listsexamplethe string stored in text would look like this'lists o...
2,634
import pyperclip text pyperclip paste(separate lines and add stars lines text split('\ 'for in range(len(lines))loop through all indexes for "lineslist lines[ 'lines[iadd star to each string in "lineslist text '\njoin(linespyperclip copy(textwhen this program is runit replaces the text on the clipboard with text that h...
2,635
piglatin append(prefixnonletterscontinue separate the non-letters at the end of this wordsuffixnonletters 'while not word[- isalpha()suffixnonletters +word[- word word[:- remember if the word was in uppercase or title case wasupper word isupper(wastitle word istitle(word word lower(make the word lowercase for translati...
2,636
translate them into pig latinpiglatin [ list of the words in pig latin for word in message split()separate the non-letters at the start of this wordprefixnonletters 'while len(word and not word[ isalpha()prefixnonletters +word[ word word[ :if len(word= piglatin append(prefixnonletterscontinue we need each word to be it...
2,637
the consonants from the beginning of wordseparate the consonants at the start of this wordprefixconsonants 'while len(word and not word[ in vowelsprefixconsonants +word[ word word[ :we use loop similar to the loop that removed the non-letters from the start of wordexcept now we are pulling off consonants and storing th...
2,638
text is common form of dataand python comes with many helpful string methods to process the text stored in string values you will make use of indexingslicingand string methods in almost every python program you write the programs you are writing now don' seem too sophisticated-they don' have graphical user interfaces w...
2,639
what do the following expressions evaluate to'helloworld!'[ 'helloworld!'[ : 'helloworld!'[: 'helloworld!'[ :what do the following expressions evaluate to'helloupper('helloupper(isupper('helloupper(lower( what do the following expressions evaluate to'rememberrememberthe fifth of november split('-join('there can be only...
2,640
the colwidths list to find out what integer width to pass to the rjust(string method zombie dice bots programming games are game genre where instead of playing game directlyplayers write bot programs to play the game autonomously 've created zombie dice simulatorwhich allows programmers to practice their skills while m...
2,641
appendix you can run demo of the simulator with some pre-made bots by running the following in the interactive shellimport zombiedice zombiedice demo(zombie dice visualization is running open your browser to localhost: to view it press ctrl- to quit the program launches your web browserwhich will look like figure - fig...
2,642
you can choose to ignore it in your code dicerollresults zombiedice roll(first roll roll(returns dictionary with keys 'brains''shotgun'and 'footstepswith how many rolls of each type there were the 'rollskey is list of (coloricontuples with the exact roll result information example of roll(return value{'brains' 'footste...
2,643
try writing some of your own bots to play zombie dice and see how they compare against the other bots specificallytry to create the following botsa bot thatafter the first rollrandomly decides if it will continue or stop bot that stops rolling after it has rolled two brains bot that stops rolling after it has rolled tw...
2,644
au tom at ing ta sks
2,645
pat atching regul ar xpressions you may be familiar with searching for text by pressing ctrl- and entering the words you're looking for regular expressions go one step furtherthey allow you to specify pattern of text to search for you may not know business' exact phone numberbut if you live in the united states or cana...
2,646
them even though most modern text editors and word processorssuch as microsoft word or openofficehave find and find-and-replace features that can search based on regular expressions regular expressions are huge time-saversnot just for software users but also for programmers in facttech writer cory doctorow argues that ...
2,647
if not text[iisdecimal()return false return true print('is phone number?'print(isphonenumber('')print('is moshi moshi phone number?'print(isphonenumber('moshi moshi')when this program is runthe output looks like thisis phone numbertrue is moshi moshi phone numberfalse the isphonenumber(function has code that does sever...
2,648
message is assigned to the variable chunk for exampleon the first iterationi is and chunk is assigned message[ : (that isthe string 'call me at 'on the next iterationi is and chunk is assigned message[ : (the string 'all me at 'in other wordson each iteration of the for loopchunk takes on the following values'call me a...
2,649
all the regex functions in python are in the re module enter the following into the interactive shell to import this moduleimport re note most of the examples in this will require the re moduleso remember to import it at the beginning of any script you write or any time you restart mu otherwiseyou'll get nameerrorname ...
2,650
while there are several steps to using regular expressions in pythoneach step is fairly simple note import the regex module with import re create regex object with the re compile(function (remember to use raw string pass the string you want to search into the regex object' search(method this returns match object call t...
2,651
(' '' - 'areacodemainnumber mo groups(print(areacode print(mainnumber - since mo groups(returns tuple of multiple valuesyou can use the multiple-assignment trick to assign each value to separate variableas in the previous areacodemainnumber mo groups(line parentheses have special meaning in regular expressionsbut what ...
2,652
the character is called pipe you can use it anywhere you want to match one of many expressions for examplethe regular expression 'batman|tina feywill match either 'batmanor 'tina feywhen both batman and tina fey occur in the searched stringthe first occurrence of matching text will be returned as the match object enter...
2,653
'batmanmo batregex search('the adventures of batwoman'mo group('batwomanthe (wo)part of the regular expression means that the pattern wo is an optional group the regex will match text that has zero instances or one instance of wo in it this is why the regex matches both 'batwomanand 'batmanusing the earlier phone numbe...
2,654
while means "match zero or more,the (or plusmeans "match one or more unlike the starwhich does not require its group to appear in the matched stringthe group preceding plus must appear at least once it is not optional enter the following into the interactive shelland compare it with the star regexes in the previous sec...
2,655
haregex re compile( '(ha){ }'mo haregex search('hahaha'mo group('hahahamo haregex search('ha'mo =none true here(ha){ matches 'hahahabut not 'hasince it doesn' match 'ha'search(returns none greedy and non-greedy matching since (ha){ , can match threefouror five instances of ha in the string 'hahahahaha'you may wonder wh...
2,656
only on the first instance of matching textenter the following into the interactive shellphonenumregex re compile( '\ \ \ -\ \ \ -\ \ \ \ 'mo phonenumregex search('cellwork'mo group('on the other handfindall(will not return match object but list of strings--as long as there are no groups in the regular expression each ...
2,657
shorthand character class represents \ any numeric digit from to \ any character that is not numeric digit from to \ any letternumeric digitor the underscore character (think of this as matching "wordcharacters \ any character that is not letternumeric digitor the underscore character \ any spacetabor newline character...
2,658
for examplethe character class [ -za- - will match all lowercase lettersuppercase lettersand numbers note that inside the square bracketsthe normal regular expression symbols are not interpreted as such this means you do not need to escape the *?or (characters with preceding backslash for examplethe character class [ -...
2,659
and end with one or more numeric characters enter the following into the interactive shellwholestringisnum re compile( '^\ +$'wholestringisnum search(' 'wholestringisnum search(' xyz '=none true wholestringisnum search(' '=none true the last two search(calls in the previous interactive shell example demonstrate how the...
2,660
possible to match any and all text in non-greedy fashionuse the dotstarand question mark *?like with bracesthe question mark tells python to match in non-greedy way enter the following into the interactive shell to see the difference between the greedy and non-greedy versionsnongreedyregex re compile( ''mo nongreedyreg...
2,661
this covered lot of notationso here' quick review of what you learned about basic regular expression syntaxthe matches zero or one of the preceding group the matches zero or more of the preceding group the matches one or more of the preceding group the {nmatches exactly of the preceding group the { ,matches or more of ...
2,662
regular expressions can not only find text patterns but can also substitute new text in place of those patterns the sub(method for regex objects is passed two arguments the first argument is string to replace any matches the second is the string for the regular expression the sub(method returns string with the substitu...
2,663
)'''re verboseextension note how the previous example uses the triple-quote syntax ('''to create multiline string so that you can spread the regular expression definition over many linesmaking it much more legible the comment rules inside the regular expression string are the same as regular python codethe symbol and e...
2,664
into writing code but more often than notit' best to take step back and consider the bigger picture recommend first drawing up high-level plan for what your program needs to do don' think about the actual code yet-you can worry about that later right nowstick to broad strokes for exampleyour phone and email address ext...
2,665
replaced as you write the actual code the phone number begins with an optional area codeso the area code group is followed with question mark since the area code can be just three digits (that is\ { }or three digits within parentheses (that is\(\ { }\))you should have pipe joining those parts you can add the regex comm...
2,666
really be dot-anything this is between two and four characters the format for email addresses has lot of weird rules this regular expression won' match every possible valid email addressbut it'll match almost any typical email address you'll encounter step find all matches in the clipboard text now that you have specif...
2,667
now that you have the email addresses and phone numbers as list of strings in matchesyou want to put them on the clipboard the pyperclip copy(function takes only single string valuenot list of stringsso you call the join(method on matches to make it easier to see that the program is workinglet' print any matches you fi...
2,668
remove sensitive information such as social security or credit card numbers find common typos such as multiple spaces between wordsaccidentally accidentally repeated wordsor multiple exclamation marks at the end of sentences those are annoying!summary while computer can search for text quicklyit must be told precisely ...
2,669
regular expressions what is the difference between and *? what is the character class syntax to match all numbers and lowercase letters how do you make regular expression case-insensitive what does the character normally matchwhat does it match if re dotall is passed as the second argument to re compile() if numregex r...
2,670
'robocop eats apples 'alice throws footballs 'carol eats cats practice projects for practicewrite programs to do the following tasks date detection write regular expression that can detect dates in the dd/mm/yyyy format assume that the days range from to the months range from to and the years range from to note that if...
2,671
inpu va lidat ion input validation code checks that values entered by the usersuch as text from the input(functionare formatted correctly for exampleif you want users to enter their agesyour code shouldn' accept nonsensical answers such as negative numbers (which are outside the range of acceptable integersor words (wh...
2,672
input until they enter valid textas in the following examplewhile trueprint('enter your age:'age input(tryage int(ageexceptprint('please use numeric digits 'continue if age print('please enter positive number 'continue break print( 'your age is {age'when you run this programthe output could look like thisenter your age...
2,673
install it separately using pip to install pyinputplusrun pip install --user pyinputplus from the command line appendix has complete instructions for installing third-party modules to check if pyinputplus installed correctlyimport it in the interactive shellimport pyinputplus if no errors appear when you import the mod...
2,674
pass string to pyinputplus function' prompt keyword argument to display promptresponse input('enter number'enter number response ' import pyinputplus as pyip response pyip inputint(prompt='enter number'enter numbercat 'catis not an integer enter number response use python' help(function to find out more about each of t...
2,675
the input can be equal to themalsothe input must be greater than the greaterthan and less than the lessthan arguments (that isthe input cannot be equal to themthe blank keyword argument by defaultblank input isn' allowed unless the blank keyword argument is set to trueimport pyinputplus as pyip response pyip inputnum('...
2,676
--snip-pyinputplus timeoutexception when you use these keyword arguments and also pass default keyword argumentthe function returns the default value instead of raising an exception enter the following into the interactive shellresponse pyip inputnum(limit= default=' / 'hello 'hellois not number world 'worldis not numb...
2,677
this response is invalid response if you specify both an allowregexes and blockregexes argumentthe allow list overrides the block list for exampleenter the following into the interactive shellwhich allows 'caterpillarand 'categorybut blocks anything else that has the word 'catin itimport pyinputplus as pyip response py...
2,678
numberslist list(numbersfor idigit in enumerate(numberslist)numberslist[iint(digitif sum(numberslist! raise exception('the digits must add up to not % (sum(numberslist))return int(numbersreturn an int form of numbers response pyip inputcustom(addsuptotenno parentheses after addsuptoten here the digits must add up to no...
2,679
yes want to know how to keep an idiot busy for hoursyes want to know how to keep an idiot busy for hoursyes!!!!!'yes!!!!!!is not valid yes/no response want to know how to keep an idiot busy for hourstell me how to keep an idiot busy for hours 'tell me how to keep an idiot busy for hours is not valid yes/no response wan...
2,680
pyinputplus' features can be useful for creating timed multiplication quiz by setting the allowregexesblockregexestimeoutand limit keyword argument to pyip inputstr()you can leave most of the implementation to pyinputplus the less code you need to writethe faster you can write your programs let' create program that pos...
2,681
timeout= limit= if the user answers after the -second timeout has expiredeven if they answer correctlypyip inputstr(raises timeoutexception exception if the user answers incorrectly more than timesit raises retrylimitexception exception both of these exception types are in the pyinputplus moduleso pyip needs to prepend...
2,682
pre-selected optionswhile inputmenu(also adds numbers or letters for quick selection all of these functions have the following standard featuresstripping whitespace from the sidessetting timeout and retry limits with the timeout and limit keyword argumentsand passing lists of regular expression strings to allowregexes ...
2,683
using inputyesno(to ask if they want cheese if sousing inputmenu(to ask for cheese typecheddarswissor mozzarella using inputyesno(to ask if they want mayomustardlettuceor tomato using inputint(to ask how many sandwiches they want make sure this number is or more come up with prices for each of these optionsand have you...
2,684
re ading and writing files variables are fine way to store data while your program is runningbut if you want your data to persist even after your program has finishedyou need to save it to file you can think of file' contents as single string valuepotentially gigabytes in size in this you will learn how to use python t...
2,685
called directoriesfolders can contain files and other folders for exampleproject docx is in the documents folderwhich is inside the al folderwhich is inside the users folder figure - shows this folder organization :users ai documents project docx figure - file in hierarchy of folders the :part of the path is the root f...
2,686
'spam\\bacon\\eggsnote that the convention for importing pathlib is to run from pathlib import pathsince otherwise we' have to enter pathlib path everywhere path shows up in our code not only is this extra typing redundantbut it' also redundant ' running this interactive shell examples on windowsso path('spam''bacon''e...
2,687
we normally use the operator to add two integer or floating-point numberssuch as in the expression which evaluates to the integer value but we can also use the operator to concatenate two string valueslike the expression 'hello'world'which evaluates to the string value 'helloworldsimilarlythe operator that we normally ...
2,688
interactive shell'spam'bacon'eggstraceback (most recent call last)file ""line in typeerrorunsupported operand type(sfor /'strand 'strpython evaluates the operator from left to right and evaluates to path objectso either the first or second leftmost value must be path object for the entire expression to evaluate to path...
2,689
\programs\python\python so the filename project docx refers to :\users\al \appdata\local\programs\python\python \project docx when we change the current working directory to :\windows\system the filename project docx is interpreted as :\windows\system \project docx python will display an error if you try to change to d...
2,690
("dot-dot"means "the parent folder figure - is an example of some folders and files when the current working directory is set to :\baconthe relative paths for the other folders and files are set as they are in the figure :current working directory bacon fizz spam txt spam txt eggs spam txt spam txt relative paths absol...
2,691
examplethis code will create spam folder under the home folder on my computerfrom pathlib import path path( ' :\users\al\spam'mkdir(note that mkdir(can only make one directory at timeit won' make several subdirectories at once like os makedirs(handling absolute and relative paths the pathlib module provides methods for...
2,692
and relative pathscalling os path abspath(pathwill return string of the absolute path of the argument this is an easy way to convert relative path into an absolute one calling os path isabs(pathwill return true if the argument is an absolute path and false if it is relative path calling os path relpath(pathstartwill re...
2,693
parent name :\users\al\spam txt drive stem suffix /home/al/spam txt anchor parent name figure - the parts of windows (topand macos/linux (bottomfile path the parts of file path include the followingthe anchorwhich is the root folder of the filesystem on windowsthe drivewhich is the single letter that often denotes phys...
2,694
path cwd(windowspath(' :/users/al/appdata/local/programs/python/python 'path cwd(parents[ windowspath(' :/users/al/appdata/local/programs/python'path cwd(parents[ windowspath(' :/users/al/appdata/local/programs'path cwd(parents[ windowspath(' :/users/al/appdata/local'path cwd(parents[ windowspath(' :/users/al/appdata'p...
2,695
and os path basename(and placing their return values in tuple(os path dirname(calcfilepath)os path basename(calcfilepath)(' :\\windows\\system ''calc exe'but os path split(is nice shortcut if you need both values alsonote that os path split(does not take file path and return list of strings of each folder for thatuse t...
2,696
in sizeand have lot of files in :\windows\system if want to find the total size of all the files in this directoryi can use os path getsize(and os listdir(together totalsize for filename in os listdir(' :\\windows\\system ')totalsize totalsize os path getsize(os path join(' :\\windows\\system 'filename)print(totalsize ...
2,697
single characterlist( glob('projectdocx'[windowspath(' :/users/al/desktop/project docx')windowspath(' :/users/aldesktop/project docx')--snip-windowspath(' :/users/al/desktop/project docx')the glob expression 'projectdocxwill return 'project docxor 'project docx'but it will not return 'project docx'because only matches ...
2,698
calling is_dir(returns true if the path exists and is directoryor returns false otherwise on my computerhere' what get when try these methods in the interactive shellwindir path(' :/windows'notexistsdir path(' :/this/folder/does/not/exist'calcfile path(' :/windows /system /calc exe'windir exists(true windir is_dir(true...
2,699
figure - figure - the windows calc exe program opened in notepad since every different type of binary file must be handled in its own waythis book will not go into reading and writing raw binary files directly fortunatelymany modules make working with binary files easier--you will explore one of themthe shelve modulela...