Python之文件和异常

文件和异常

接下来就该学习文件的处理,让程序能够快速地分析大量的数据;还将学习错误处理,避免程序在面对意外情形时崩溃;还将学习异常,它们是Python创建的特殊对象,用于管理程序运行时出现的错误;还将学习模块json,它能够保存用户数据,以免在程序停止运行后丢失。

1.从文件中读取数据

文本文件可存储的数据量多得难以置信:天气数据、交通数据、社会经济数据、文学作品等。每当需要需要分析或修改再文件中的信息时,读取文件都很有用,对数据分析应用程序来说尤其如此。比如,比可以编写一个这样的程序:读取一个文本文件的内容,重新设置这些数据的格式并将其写入文件,让浏览器能够显示这些内容。
要使用文本文件的信息,首先需要将信息读取到内存中。

1.1读取整个文件

那就先创建一个文本文件吧:
pi_digits.txt

3.1415926535
  8979323846
  2643383279

然后编写python脚本程序,来读取该文件:
file_reader.py

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents)

还不错哦…

PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='51159'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.1415926535
  8979323846
  2643383279
  

在file_reader.py程序中,第一行代码做了大量的工作。**函数open()**接受一个参数:要打开的文件的名称。python在当前执行的文件所在的目录中查找指定的文件。函数open()返回一个表示文件的对象,在file_reader.py程序中返回的对象存储在file_object中。
关键字with在不再需要访问文件后将其关闭。在该程序中,注意到调用了open(),但没有调用close();也可以调用open()和close()来打开和关闭文件,但这样做时,如果程序存在bug,导致close()语句未执行,文件将不会关闭。这看似微不足道,但未妥善地关闭文件可能会导致数据丢失或受损。如果在程序中过早的调用close(),会发现需要使用文件时文件可能已经被关闭了。但是用当前的with的形式,可让python去确定关闭的时间:我们只管打开文件,并在需要时使用它,Python自会在合适的时候自动将其关闭。
拿到了pi_digits.txt的文件对象后,我们使用方法read()读取这个文件的全部内容,并将其作为一个长长的字符串存储在变量contents中,通过打印contents的值,就可以将这个文本文件中的内容显示出来。
有的时候打印出来的结果会有空行,是因为方法read()到达文件末尾时返回一个空字符串,而将这个空字符串显示出来时就是一个空行。那怎么删除这个空白行呢?大家是否还记得我们在前面说字符串的时候提到了一个方法,就是rstrip()方法:

with open('pi_digits.txt') as file_object:
    contents = file_object.read()
    print(contents.rstrip())
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='51159'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.1415926535
  8979323846
  2643383279

呢哦,现在没有空白行了吧!

1.2文件路径

在上面的例子中我们直接将pi_digits.txt这样的简单文件名传递给函数open()时,Python将当前执行的文件所在的目录中查找文件。
有时候文件会和编写的.py文件不在同一个目录下面,因为为了找到要操作的文件可使用相对文件路径来打开该文件夹中的文件。相对文件路径让python到指定的位置去查找,而该位置是相对于当前运行的程序所在目录的。在linux和OS X中,可以如下形式编写代码:

with open('text_files/filename.txt')as file_object:

这行代码让python到文件夹python_work下的文件夹text_file中去查找指定的.txt文件,在Windows系统中,在文件路径中使用反斜杠(\)而不是斜杠(/):

with open('text_file\filename.txt') as file_object:

当然还可以把文件在计算机中的准确位置告诉python,这样就不用关心当前运行的程序存储在什么地方了,该准确路径称为绝对路径,在linux和OS X中,绝对路径如下编写:

with open('/home/ehmatthes/other_files/text_files/filename.txt') as file_object:

那再windows下面呢?因为前面说win和其它两个有些区别,再win中如下:

with opne('C:\Users\ehmatthes\other_files\text_files\filename.txt') as file_object:

上面的代码中,我们发现文件的绝对路径一般都很长,为了简便写,不用重复写很多遍,我们可以把绝对路径存储再一个变量中,如下:

file_path = '/home/ehmatthes/other_files/text_files/filename.txt'
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'

注:Windows系统有时能够正确地解读文件路径中的斜杠。如果你使用的是windows系统,且结果不符合预期,请确保再文件路径中使用的是反斜杠。另外,由于反斜杠再Python中被视为转义标记,为在Windows中确保万无一失,应以原始字符串的方式指定路径,即在开头的单引号前加上r。

1.3逐行读取

读取文件时,常常需要检查其中的每一行:可能要在文件中查找特定的信息,或者要以某种方式修改文件中的文本。比如,可能要遍历一个包含天气数据的文件,并使用天气描述中包含字样sunny的行。在新闻报道中,可能会查找包含标签的行,并按特定的格式设置它。
要以每次一行的方式检查文件,可对文件对象使用for循环:
file_reader.py

filename = 'pi_digits.txt'

with open(filename) as file_object:
    for line in file_object:
        print(line.rstrip())
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='53819'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.1415926535
  8979323846
  2643383279

1.4创建一个包含文件各行内容的列表

使用关键字with时,open()返回的文件对象只在with代码块内可用。如果要在with代码块外访问文件的内容,可在with代码块内将文件的各行存储在一个列表中,并在with代码块外使用该列表:你可以立即处理文件的各个部分,也可推迟到程序后面再处理。
下面的示例在with代码块中将文件pi_digits.txt的各行存储在一个列表中,再在with代码块外打印它们:

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.rstrip())
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='54163'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.1415926535
  8979323846
  2643383279

方法readlines()从文件中读取每一行,并将其存储在一个列表中;接下来该列表被存储到变量lines中;在with代码块外,我们依然可以使用这个变量。

1.5使用文件的内容

将文件读取到内存中后,就可以以任何方式使用这些数据了。下面来举例,以简单的方式使用圆周率的值。首先,我们创建一个字符串,它包含文件中存储的所有数字,且没有任何空格:
pi_string.py

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string += line.rstrip()

print(pi_string)
print(len(pi_string))
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='55126'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.1415926535  8979323846  2643383279
36

在这个例子中,首先打开文件,并将其中的所有行都存储在一个列表中,接着创建一个变量-----pi_string,用于存储圆周率的值,然后使用循环将各行都加入pi_string,并删除了每行末尾的换行符。但我们发现在输出的结果中,还是有一个空格,那能不能把中间的空格给去掉呢?当然可以,程序就是来解决人类生活中的问题和改善人类生活的嘛。
在变量pi_string存储的字符串中,包含原来位于每行左边的空格,为删除这些空格,可使用strip(),不用rstrip():

filename = 'pi_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='55413'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.141592653589793238462643383279
32

怎么样?还可以吧,我们获得了一个包含精确到30位小数的圆周率值。这个字符串长32字符,包含了整数部分的3和小数点。
*注:读取文本文件时,Python将其中的所有文本都解读为字符串。如果你读取的是数字,并要将其作为数值使用,就必须使用*函数int()将其转换为整数,或使用函数float()将其转换为浮点数

1.6包含一百万位的大型文件

上面的例子中都是一个只有三行的文本文件,但这些代码示例也可以处理非常大的文件。比如,有一个包含精确到小数点后1000000位而不是30位的圆周率值,也可以创建一个包含所有这些数字的字符串。

filename = 'D:\python\《Python编程》源代码文件-更新\《Python编程》源代码文件\chapter_10\pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string += line.strip()

print(pi_string)
print(len(pi_string))
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='55545'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
3.14159265358979323846264338327950288419716939937510582097494459230781640628620899862803482534211706798214808651328230664709384460955058223172535940812848111745028410270193852110555964462294895493038196442881097566593344612847564823378678316527120190914564856692346034861045432664821339360726024914127372458700660631558817488152092096282925409171536436789259036001133053054882046652138414695194151160943305727036575959195309218611738193261179310511854807446237996274956735188575272489122793818301194912983367336244065664308602139494639522473719070217986094370277053921717629317675238467481846766940513200056812714526356082778577134275778960917363717872146844090122495343014654958537105079227968925892354201995611212902196086403441815981362977477130996051870721134999999837297804995105973173281609631859502445945534690830264252230825334468503526193118817101000313783875288658753320838142061717766914730359825349042875546873115956286388235378759375195778185778053217122680661300192787661119590921642019893809525720106548586327886593615338182796823030195203530185296899577362259941389124972177528347913151557485724245415069595082953311686172785588907509838175463746493931925506040092770167113900984882401285836160356370766010471018194295559619894676783744944825537977472684710404753464620804668425906949129331367702898915210475216205696602405803815019351125338243003558764024749647326391419927260426992279678235478163600934172164121992458631503028618297455570674983850549458858692699569092721079750930295532116534498720275596023648066549911988183479775356636980742654252786255181841757467289097777279380008164706001614524919217321721477235014144197356854816136115735255213347574184946843852332390739414333454776241686251898356948556209921922218427255025425688767179049460165346680498862723279178608578438382796797668145410095388378636095068006422512520511739298489608412848862694560424196528502221066118630674427862203919494504712371378696095636437191728746776465757396241389086583264599581339047802759009946576407895126946839835259570982582262052248940772671947826848260147699090264013639443745530506820349625245174939965143142980919065925093722169646151570985838741059788595977297549893016175392846813826868386894277415599185592524595395943104997252468084598727364469584865383673622262609912460805124388439045124413654976278079771569143599770012961608944169486855584840635342207222582848864815845602850601684273945226746767889525213852254995466672782398645659611635488623057745649803559363456817432411251507606947945109659609402522887971089314566913686722874894056010150330861792868092087476091782493858900971490967598526136554978189312978482168299894872265880485756401427047755513237964145152374623436454285844479526586782105114135473573952311342716610213596953623144295248493718711014576540359027993440374200731057853906219838744780847848968332144571386875194350643021845319104848100537061468067491927819119793995206141966342875444064374512371819217999839101591956181467514269123974894090718649423196156794520809514655022523160388193014209376213785595663893778708303906979207734672218256259966150142150306803844773454920260541466592520149744285073251866600213243408819071048633173464965145390579626856100550810665879699816357473638405257145910289706414011097120628043903975951567715770042033786993600723055876317635942187312514712053292819182618612586732157919841484882916447060957527069572209175671167229109816909152801735067127485832228718352093539657251210835791513698820914442100675103346711031412671113699086585163983150197016515116851714376576183515565088490998985998238734552833163550764791853589322618548963213293308985706420467525907091548141654985946163718027098199430992448895757128289059232332609729971208443357326548938239119325974636673058360414281388303203824903758985243744170291327656180937734440307074692112019130203303801976211011004492932151608424448596376698389522868478312355265821314495768572624334418930396864262434107732269780280731891544110104468232527162010526522721116603966655730925471105578537634668206531098965269186205647693125705863566201855810072936065987648611791045334885034611365768675324944166803962657978771855608455296541266540853061434443185867697514566140680070023787765913440171274947042056223053899456131407112700040785473326993908145466464588079727082668306343285878569830523580893306575740679545716377525420211495576158140025012622859413021647155097925923099079654737612551765675135751782966645477917450112996148903046399471329621073404375189573596145890193897131117904297828564750320319869151402870808599048010941214722131794764777262241425485454033215718530614228813758504306332175182979866223717215916077166925474873898665494945011465406284336639379003976926567214638530673609657120918076383271664162748888007869256029022847210403172118608204190004229661711963779213375751149595015660496318629472654736425230817703675159067350235072835405670403867435136222247715891504953098444893330963408780769325993978054193414473774418426312986080998886874132604721569516239658645730216315981931951673538129741677294786724229246543668009806769282382806899640048243540370141631496589794092432378969070697794223625082216889573837986230015937764716512289357860158816175578297352334460428151262720373431465319777741603199066554187639792933441952154134189948544473456738316249934191318148092777710386387734317720754565453220777092120190516609628049092636019759882816133231666365286193266863360627356763035447762803504507772355471058595487027908143562401451718062464362679456127531813407833033625423278394497538243720583531147711992606381334677687969597030983391307710987040859133746414428227726346594704745878477872019277152807317679077071572134447306057007334924369311383504931631284042512192565179806941135280131470130478164378851852909285452011658393419656213491434159562586586557055269049652098580338507224264829397285847831630577775606888764462482468579260395352773480304802900587607582510474709164396136267604492562742042083208566119062545433721315359584506877246029016187667952406163425225771954291629919306455377991403734043287526288896399587947572917464263574552540790914513571113694109119393251910760208252026187985318877058429725916778131496990090192116971737278476847268608490033770242429165130050051683233643503895170298939223345172201381280696501178440874519601212285993716231301711444846409038906449544400619869075485160263275052983491874078668088183385102283345085048608250393021332197155184306354550076682829493041377655279397517546139539846833936383047461199665385815384205685338621867252334028308711232827892125077126294632295639898989358211674562701021835646220134967151881909730381198004973407239610368540664319395097901906996395524530054505806855019567302292191393391856803449039820595510022635353619204199474553859381023439554495977837790237421617271117236434354394782218185286240851400666044332588856986705431547069657474585503323233421073015459405165537906866273337995851156257843229882737231989875714159578111963583300594087306812160287649628674460477464915995054973742562690104903778198683593814657412680492564879855614537234786733039046883834363465537949864192705638729317487233208376011230299113679386270894387993620162951541337142489283072201269014754668476535761647737946752004907571555278196536213239264061601363581559074220202031872776052772190055614842555187925303435139844253223415762336106425063904975008656271095359194658975141310348227693062474353632569160781547818115284366795706110861533150445212747392454494542368288606134084148637767009612071512491404302725386076482363414334623518975766452164137679690314950191085759844239198629164219399490723623464684411739403265918404437805133389452574239950829659122850855582157250310712570126683024029295252201187267675622041542051618416348475651699981161410100299607838690929160302884002691041407928862150784245167090870006992821206604183718065355672525325675328612910424877618258297651579598470356222629348600341587229805349896502262917487882027342092222453398562647669149055628425039127577102840279980663658254889264880254566101729670266407655904290994568150652653053718294127033693137851786090407086671149655834343476933857817113864558736781230145876871266034891390956200993936103102916161528813843790990423174733639480457593149314052976347574811935670911013775172100803155902485309066920376719220332290943346768514221447737939375170344366199104033751117354719185504644902636551281622882446257591633303910722538374218214088350865739177150968288747826569959957449066175834413752239709683408005355984917541738188399944697486762655165827658483588453142775687900290951702835297163445621296404352311760066510124120065975585127617858382920419748442360800719304576189323492292796501987518721272675079812554709589045563579212210333466974992356302549478024901141952123828153091140790738602515227429958180724716259166854513331239480494707911915326734302824418604142636395480004480026704962482017928964766975831832713142517029692348896276684403232609275249603579964692565049368183609003238092934595889706953653494060340216654437558900456328822505452556405644824651518754711962184439658253375438856909411303150952617937800297412076651479394259029896959469955657612186561967337862362561252163208628692221032748892186543648022967807057656151446320469279068212073883778142335628236089632080682224680122482611771858963814091839036736722208883215137556003727983940041529700287830766709444745601345564172543709069793961225714298946715435784687886144458123145935719849225284716050492212424701412147805734551050080190869960330276347870810817545011930714122339086639383395294257869050764310063835198343893415961318543475464955697810382930971646514384070070736041123735998434522516105070270562352660127648483084076118301305279320542746286540360367453286510570658748822569815793678976697422057505968344086973502014102067235850200724522563265134105592401902742162484391403599895353945909440704691209140938700126456001623742880210927645793106579229552498872758461012648369998922569596881592056001016552563756785667227966198857827948488558343975187445455129656344348039664205579829368043522027709842942325330225763418070394769941597915945300697521482933665556615678736400536665641654732170439035213295435291694145990416087532018683793702348886894791510716378529023452924407736594956305100742108714261349745956151384987137570471017879573104229690666702144986374645952808243694457897723300487647652413390759204340196340391147320233807150952220106825634274716460243354400515212669324934196739770415956837535551667302739007497297363549645332888698440611964961627734495182736955882207573551766515898551909866653935494810688732068599075407923424023009259007017319603622547564789406475483466477604114632339056513433068449539790709030234604614709616968868850140834704054607429586991382966824681857103188790652870366508324319744047718556789348230894310682870272280973624809399627060747264553992539944280811373694338872940630792615959954626246297070625948455690347119729964090894180595343932512362355081349490043642785271383159125689892951964272875739469142725343669415323610045373048819855170659412173524625895487301676002988659257866285612496655235338294287854253404830833070165372285635591525347844598183134112900199920598135220511733658564078264849427644113763938669248031183644536985891754426473998822846218449008777697763127957226726555625962825427653183001340709223343657791601280931794017185985999338492354956400570995585611349802524990669842330173503580440811685526531170995708994273287092584878944364600504108922669178352587078595129834417295351953788553457374260859029081765155780390594640873506123226112009373108048548526357228257682034160504846627750450031262008007998049254853469414697751649327095049346393824322271885159740547021482897111777923761225788734771881968254629812686858170507402725502633290449762778944236216741191862694396506715157795867564823993917604260176338704549901761436412046921823707648878341968968611815581587360629386038101712158552726683008238340465647588040513808016336388742163714064354955618689641122821407533026551004241048967835285882902436709048871181909094945331442182876618103100735477054981596807720094746961343609286148494178501718077930681085469000944589952794243981392135055864221964834915126390128038320010977386806628779239718014613432445726400973742570073592100315415089367930081699805365202760072774967458400283624053460372634165542590276018348403068113818551059797056640075094260878857357960373245141467867036880988060971642584975951380693094494015154222219432913021739125383559150310033303251117491569691745027149433151558854039221640972291011290355218157628232831823425483261119128009282525619020526301639114772473314857391077758744253876117465786711694147764214411112635835538713610110232679877564102468240322648346417663698066378576813492045302240819727856471983963087815432211669122464159117767322532643356861461865452226812688726844596844241610785401676814208088502800541436131462308210259417375623899420757136275167457318918945628352570441335437585753426986994725470316566139919996826282472706413362221789239031760854289437339356188916512504244040089527198378738648058472689546243882343751788520143956005710481194988423906061369573423155907967034614914344788636041031823507365027785908975782727313050488939890099239135033732508559826558670892426124294736701939077271307068691709264625484232407485503660801360466895118400936686095463250021458529309500009071510582362672932645373821049387249966993394246855164832611341461106802674466373343753407642940266829738652209357016263846485285149036293201991996882851718395366913452224447080459239660281715655156566611135982311225062890585491450971575539002439315351909021071194573002438801766150352708626025378817975194780610137150044899172100222013350131060163915415895780371177927752259787428919179155224171895853616805947412341933984202187456492564434623925319531351033114763949119950728584306583619353693296992898379149419394060857248639688369032655643642166442576079147108699843157337496488352927693282207629472823815374099615455987982598910937171262182830258481123890119682214294576675807186538065064870261338928229949725745303328389638184394477077940228435988341003583854238973542439564755568409522484455413923941000162076936368467764130178196593799715574685419463348937484391297423914336593604100352343777065888677811394986164787471407932638587386247328896456435987746676384794665040741118256583788784548581489629612739984134427260860618724554523606431537101127468097787044640947582803487697589483282412392929605829486191966709189580898332012103184303401284951162035342801441276172858302435598300320420245120728725355811958401491809692533950757784000674655260314461670508276827722235341911026341631571474061238504258459884199076112872580591139356896014316682831763235673254170734208173322304629879928049085140947903688786878949305469557030726190095020764334933591060245450864536289354568629585313153371838682656178622736371697577418302398600659148161640494496501173213138957470620884748023653710311508984279927544268532779743113951435741722197597993596852522857452637962896126915723579866205734083757668738842664059909935050008133754324546359675048442352848747014435454195762584735642161981340734685411176688311865448937769795665172796623267148103386439137518659467300244345005449953997423723287124948347060440634716063258306498297955101095418362350303094530973358344628394763047756450150085075789495489313939448992161255255977014368589435858775263796255970816776438001254365023714127834679261019955852247172201777237004178084194239487254068015560359983905489857235467456423905858502167190313952629445543913166313453089390620467843877
1000002

是不是很强大,确实挺厉害,并且运行时间也挺快的,对于你可以处理的数据量,Python没有任何限制;只要系统的内存足够大,想处理多少数据都可以。
我们看到输出的结果太长了,那要是只想输出部分怎么做呢?我们来看看怎么只输出部分:

filename = 'D:\python\《Python编程》源代码文件-更新\《Python编程》源代码文件\chapter_10\pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string += line.strip()

print(pi_string[:52] + "...")
print(len(pi_string))

我们可以使用前面列表的切片方法,只输出前52个数值。

3.14159265358979323846264338327950288419716939937510...
1000002

1.7圆周率值中包含你的生日吗?

我们做个有趣的小实验,就是看看我们自己的生日是否包含在圆周率中,我们可将生日表示为一个由数字组成的字符串,再检查这个字符串是否包含在pi_string中:

filename = 'D:\python\《Python编程》源代码文件-更新\《Python编程》源代码文件\chapter_10\pi_million_digits.txt'

with open(filename) as file_object:
    lines = file_object.readlines()

pi_string = ''

for line in lines:
    pi_string += line.strip()

birthday = input("Please enter your birthday, in the form mmddyy: ")
if birthday in pi_string:
    print("Your birthday appears in the first million digits of pi!")
else:
    print("Your birthday does not appear in the first million digits of pi!")
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='55651'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
**Please enter your birthday, in the form mmddyy: 05042000
Your birthday does not appear in the first million digits of pi!**
PS C:\Users\Administrator>  ${env:DEBUGPY_LAUNCHER_PORT}='55663'; & 'C:\Users\Administrator\AppData\Local\Microsoft\WindowsApps\PythonSoftwareFoundation.Python.3.8_qbz5n2kfra8p0\python.exe' 'c:\Users\Administrator\.vscode\extensions\ms-python.python-2020.4.76186\pythonFiles\lib\python\debugpy\no_wheels\debugpy\launcher' 'c:\Users\Administrator\Desktop\python\0503\file_reader.py' 
**Please enter your birthday, in the form mmddyy: 120372
Your birthday appears in the first million digits of pi!**

练习:

filename = 'learning_python.txt'

with open(filename,encoding='utf8') as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.strip())

在这里有一个小插曲,因为在前面的章节中没有提到怎么读取中文,就是说中文和英文的提取是由区别的,关于字符编码的问题,在后续的章节中,会专门的一章节来说明和学习,这次的解决方法是在open()函数的参数里面加入encoding=‘utf8’,代表是utf压缩的,解压也需要使用utf8格式。
learning_python.txt

第一章:变量和简单数据类型
第二章:列表简介
第三章:操作列表
第四章:if语句
第五章:字典
第六章:用户输入和while循环
第七章:函数
第八章:类
第九章:文件和异常
第十章:测试代码

看看运行结果如何:

第一章:变量和简单数据类型
第二章:列表简介
第三章:操作列表
第四章:if语句
第五章:字典
第六章:用户输入和while循环
第七章:函数
第八章:类
第九章:文件和异常
第十章:测试代码
filename = 'learning_python.txt'

"""读取整个文件,并打印"""
with open(filename,encoding='utf8') as file_object:
    file = file_object.read()
    print(file)
print("\n")
"""读取整个文件,并逐行打印"""
with open(filename,encoding='utf8') as file_object:
    for line in file_object:
        print(line.rstrip())

print("\n")

"""读取整个文件,然后存储到一个列表中,逐行打印"""
with open(filename,encoding='utf8') as file_object:
    lines = file_object.readlines()

for line in lines:
    print(line.strip())
第一章:变量和简单数据类型
第二章:列表简介
第三章:操作列表
第四章:if语句
第五章:字典
第六章:用户输入和while循环
第七章:函数
第八章:类
第九章:文件和异常
第十章:测试代码


第一章:变量和简单数据类型
第二章:列表简介
第三章:操作列表
第四章:if语句
第五章:字典
第六章:用户输入和while循环
第七章:函数
第八章:类
第九章:文件和异常
第十章:测试代码


第一章:变量和简单数据类型
第二章:列表简介
第三章:操作列表
第四章:if语句
第五章:字典
第六章:用户输入和while循环
第七章:函数
第八章:类
第九章:文件和异常
第十章:测试代码

练习:
replace()方法,可将字符串中的特定单词都替换为另一个单词。比如:

>>> message = "I really like dogs."
>>> message.replace('dog','cat')
'I really like cats.'

learning_python.txt

In Python you can store as much information as you want.
In Python you can connect pieces of information.
In Python you can model real-world situations.

read_file.py

filename = 'learning_python.txt'
with open(filename) as f:
    lines = f.readlines()

for line in lines:
    # Get rid of newline, then replace Python with C.
    line = line.rstrip()
    print("Original: " + line)

print("\n")
print("below is new output!\n")

for line in lines:
    # Get rid of newline, then replace Python with C.
    line = line.rstrip()
    print(line.replace('Python', 'C'))

output:

Original: In Python you can store as much information as you want.
Original: In Python you can connect pieces of information.
Original: In Python you can model real-world situations.

below is new output!

In C you can store as much information as you want.
In C you can connect pieces of information.
In C you can model real-world situations.
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值