Read and write files
Read
Import TimedefMain ():"""Read and write the file, note the use of open and the input of the file address. : Return:"""Temp= Open ('Abcd/hello.txt','R', encoding='Utf-8') Contents=Temp.readlines () forContentinchContents:Print(content) Time.sleep (1)
Temp.close ()if __name__=='__main__': Main ()
Write
defMain ():Try: With open ('Abcd/hello.txt','W', encoding='Utf-8') as Fs:fs.write ('Omni') exceptFilenotfounderror:Print('cannot open') exceptIOError as E:Print(e)if __name__=='__main__': Main ()
Read and Write
defMain ():Try: With open ('abcd/a.jpg','RB') as Fs1:date=Fs1.read () with open ('efg/b.jpg','WB') as Fs2:fs2.write (date)exceptFilenotfounderror:Print('cannot open') exceptIOError:Print('Read and write errors') Print('End of program execution')if __name__=='__main__': Main ()
Crawling pictures on the network
ImportJSONImportRequestsdefMain (): Resp= Requests.get ('http://api.tianapi.com/nba/?key=81085f5747a59581327b29d1bccfb925&num=10') Mydict=json.loads (Resp.text)Print(mydict) forTempdictinchmydict['newslist']: Pic_url= tempdict['Picurl'] Resp=requests.get (pic_url) filename= Pic_url[pic_url.rfind ('/') + 1:] Try: With open (filename,'WB') as Fs:fs.write (resp.content)exceptIOError as E:Print(e)if __name__=='__main__': Main ()
Python's third-week file read-write and simple crawler introduction