python文件和异常
来源:互联网 发布:数据库一致性错误修复 编辑:程序博客网 时间:2024/06/16 08:26
#encoding:utf-8#读取文件'''关键字with在不再需要访问文件时将其关闭'''with open('pi_digits.txt') as file_object: contents = file_object.read() #read()把文件的全部内容读取成一个长长的字符串 print(contents.rstrip()) #rstrip()的作用是删除字符串末尾的空白#绝对文件路径读取文件print("\n")file_path = '/home/shihao/Desktop/python_work/pi_digits.txt'with open(file_path) as file_object: contents = file_object.read() print(contents.rstrip())#逐行读取文件内容print("\n")file_name = 'pi_digits.txt'with open(file_name) as file_object: for line in file_object: print(line.rstrip())#创建一个包含文件各行内容的列表print("\n")file_name = 'pi_digits.txt'with open(file_name) as file_object: lines = file_object.readlines() #readlines()从文件中读取每一行,并将其存放在一个列表中for line in lines: print(line.rstrip())#写入文件file_name = 'programming.txt'with open(file_name, 'w') as file_object: file_object.write("I love proggramming.\n") #write()将一个字符串写入文件 file_object.write("I am shihao\n")#附加到文件file_name = 'programming.txt'with open(file_name, 'a') as file_object: file_object.write("I love you!")
#encoding:utf-8#处理ZeroDivisionErrortry: print(5/0)except ZeroDivisionError: print("You can't divide by zero!")#处理FileNotFoundErrortry: file_name = 'alice.txt' with open(file_name) as file_object: contents = file_object.read()except FileNotFoundError: print("The file " + file_name + " not found")
#encoding:utf-8#使用json.dump()来存储数据列表import jsonnumbers = [2, 3, 5, 7, 11, 13]file_name = 'numbers.json'with open(file_name, 'w') as f_obj: json.dump(numbers, f_obj)#使用json.load()读取列表到内存中with open(file_name) as f_obj: numbers = json.load(f_obj)print(numbers)
阅读全文
1 0
- python文件和异常
- Python 文件 和 异常处理
- Python -- 9. 文件和异常
- [Python]学习笔记之文件和异常
- python笔记-012-文件和异常
- python之文件读写和异常处理
- Python 文件 异常处理
- python文件与异常
- Python异常和异常处理
- learn with python-第十一章:文件和异常
- Python学习笔记(9)-文件和异常
- Python学习笔记06-类与文件和异常
- Python学习笔记(五):文件和异常
- Python错误和异常
- python错误和异常
- python错误和异常
- Python错误和异常
- python异常和错误
- 1.1数组和链表:189. Rotate Array(Leetcode)
- java连接数据库方式(三):MyBatis 与Spring整合
- 剑指offer[一]:二维数组中的查找(java和c++版本)
- 黑马java全套视频教程 黑马javaee传智播客 32期 28期+20套项目
- DOS窗口的一些简单介绍
- python文件和异常
- c++stl的bitset位集合容器
- HTML5拖拽
- 怎么解决VMware“该虚拟机似乎正在使用中”问题
- linux下mysql的安装
- 你可能不知道的陷阱:C#委托和事件的困惑
- hDU 2501-Tiling_easy version
- 常见的语言表示模型(词嵌入、句表示、篇章表示)
- jquery对象和dom对象的区别,如$("#imgId")[0].src; 中[0]的作用