Python学习笔记 Day11 文件和异常
2018-12-11 20:29
295 查看
Day 11 文件和异常
- 从文件读取数据
一次性读取全部文件内容
with open('pi_digits.txt') as file_object: contents =file_object.read()
函数open()用于打开文件,参数位文件名,返回值位文件对象; - 关键字with在不需要访问文件后自动完成关闭工作;
file_name = "pi_digits.txt" with open(file_name) as file_object: for line in file_object: print (line.rstrip())
-
从输出结果看,open返回的file_object应该是一个列表类型的变量;
with open(file_name) as file_object: lines = file_object.readlines() for line in lines: print (line.rstrip())
file_name = "pi_million_digits.txt" with open(file_name) as file_object: lines = file_object.readlines() pi_string = '' for line in lines: pi_string += line.rstrip() print (pi_string) print (len(pi_string))
-
with open(filename, ‘w’) as file_object:
filename = 'programming.txt' with open(filename, 'w') as file_object: file_object.write("I love programming!")
- open的第二个实参: ‘r’:只读模式打开
- ’w’:写入模式打开
- ‘a’:附加模式打开
- ’r+‘:读取和写入模式打开
- 默认以只读方式打开文件。
-
python程序执行过程中发生错误是,会产生一个异常对象,如果编写了处理该异常的代码,程序继续运行,否则,程序将停止,并显示一个traceback。
try: answer = int(first_number) / int(second_number) except ZeroDivisionError: print("You can't divide bu 0!") else: print(answer)
filename = 'alice.txt' try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: #计算文件大致包含多少个单词 words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.")
#定义计算文件有多少个单词的函数 def count_words(filename): try: with open(filename) as f_obj: contents = f_obj.read() except FileNotFoundError: msg = "Sorry, the file " + filename + " does not exist." print(msg) else: #计算文件大致包含多少个单词 words = contents.split() num_words = len(words) print("The file " + filename + " has about " + str(num_words) + " words.") filenames = ['alice.txt', 'siddhartha.txt', 'moby_dick.txt', 'little_women.txt'] for filename in filenames: count_words(filename)
相关文章推荐
- python基础学习笔记-文件与异常
- Python学习笔记(9)-文件和异常
- Head First Python学习笔记2——文件与异常
- [Python]学习笔记之文件和异常
- 阿齐兹的Python学习笔记——文件与异常
- Python学习笔记06-类与文件和异常
- Python学习笔记三(文件与异常)
- Python的学习笔记——文件与异常
- Python学习笔记--文件读写
- Python学习笔记整理(七)Python中的元组和文件及其他
- python 学习笔记 5 -- 文件输入输出
- python学习笔记——异常
- NetworkX学习笔记-3-Python中输出Gephi文件格式的方法
- python学习笔记九——文件与目录
- python学习笔记2 Python文件处理
- python学习手册笔记--第9章--元组文件及其他
- python 系统学习笔记(八)---文件操作
- Python学习笔记(七):元组、文件及其他类型
- Python 学习笔记 (3)—— python异常处理
- python基础教程_学习笔记10:异常