Python 文件和异常
Posted
tags:
篇首语:本文由小常识网(cha138.com)小编为大家整理,主要介绍了Python 文件和异常相关的知识,希望对你有一定的参考价值。
一、从文件中读取数据
#!/usr/bin/env python with open(‘pi‘) as file_object: contents = file_object.read() print(contents) =================================== 3.1415926 5212533 2324255
1、逐行读取
#!/usr/bin/env python filename = ‘pi‘ with open(filename) as file_object: for line in file_object: print(line) =================================== 3.1415926 5212533 2324255
#!/usr/bin/env python filename = ‘pi‘ with open(filename) as file_object: for line in file_object: print(line.rstrip()) ================== 3.1415926 5212533 2324255
2、创建一个包含文件各行内容的列表
#!/usr/bin/env python filename = ‘pi‘ with open(filename) as file_object: lines = file_object.readlines() #readlines()方法是从文件中读取每一行,并将其存储在一个列表中 for line in lines: print(line.rstrip()) ============================== 3.1415926 5212533 2324255
3、使用文件内容
#!/usr/bin/env python filename = ‘pi‘ 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)) ======================================== 3.141592652125332324255 23
二、写入文件
1、写入空文件
#!/usr/bin/env python filename = ‘programming.txt‘ with open(filename,‘w‘) as file_object: file_object.write("I love programming!")
2、写入多行
#!/usr/bin/env python filename = ‘programming.txt‘ with open(filename,‘w‘) as file_object: file_object.write("I love programming!\n") file_object.write("yes!\n")
3、附加到文件
#!/usr/bin/env python filename = ‘pi‘ with open(filename,‘a‘) as file_object: file_object.write("I love programming!\n") file_object.write("yes!\n")
三、异常
1、使用try-except代码块
#!/usr/bin/env python try: print(5/0) except ZeroDivisionError: print("You cant divide by zero!")
以上是关于Python 文件和异常的主要内容,如果未能解决你的问题,请参考以下文章
使用实体框架迁移时 SQL Server 连接抛出异常 - 添加代码片段
我在哪里更改此 Python 代码片段以将临时文件保存在 tmp 文件夹中?
解决未能加载文件或程序集“Newtonsoft.Json ...."或它的某一个依赖项。找到的程序集清单定义与程序集引用不匹配。 (异常来自 HRESULT:0x80131040)(代码片段