文件的读写
读
import time def main(): """ 文件的读写,注意open的用法以及,文件地址的输入。 :return: """ temp = open(‘abcd/hello.txt‘, ‘r‘, encoding=‘utf-8‘) contents = temp.readlines() for content in contents: print(content) time.sleep(1)
temp.close() if __name__ == ‘__main__‘: main()
写
def main(): try: with open(‘abcd/hello.txt‘, ‘w‘, encoding=‘utf-8‘) as fs: fs.write(‘奥尼‘) except FileNotFoundError: print(‘无法打开‘) except IOError as e: print(e) if __name__ == ‘__main__‘: main()
读和写
def main(): try: with open(‘abcd/a.jpg‘, ‘rb‘) as fs1: date = fs1.read() with open(‘efg/b.jpg‘, ‘wb‘) as fs2: fs2.write(date) except FileNotFoundError: print(‘无法打开‘) except IOError: print(‘读写错误‘) print(‘程序执行结束‘) if __name__ == ‘__main__‘: main()
爬网络上的图片
import json import requests def main(): resp = requests.get(‘http://api.tianapi.com/nba/?key=81085f5747a59581327b29d1bccfb925&num=10‘) mydict = json.loads(resp.text) print(mydict) for tempdict in mydict[‘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) except IOError as e: print(e) if __name__ == ‘__main__‘: main()