一、从文件中读取数据
#!/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! ") file_object.write("yes! ")
3、附加到文件
#!/usr/bin/env python filename = 'pi' with open(filename,'a') as file_object: file_object.write("I love programming! ") file_object.write("yes! ")
三、异常
1、使用try-except代码块
#!/usr/bin/env python try: print(5/0) except ZeroDivisionError: print("You cant divide by zero!")