Python files and exceptions,
I. Reading data from a file
#!/usr/bin/env pythonwith open('pi') as file_object: contents = file_object.read() print(contents)===================================3.1415926 5212533 2324255
1. Read data row by row
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: for line in file_object: print(line)===================================3.1415926 5212533 2324255
#!/usr/bin/env pythonfilename = 'pi'with open(filename) as file_object: for line in file_object: print(line.rstrip())==================3.1415926 5212533 2324255
2. Create a list containing the content of each row of the file
#! /Usr/bin/env pythonfilename = 'pi' with open (filename) as file_object: lines = file_object.readlines () # The readlines () method reads each row from the file, and store it in a list for line in lines: print (line. rstrip () ============================ 3.1415926 5212533
3. Use the File Content
#!/usr/bin/env pythonfilename = '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.14159265212533232425523
Ii. Writing files
1. Write an empty file
#!/usr/bin/env pythonfilename = 'programming.txt'with open(filename,'w') as file_object: file_object.write("I love programming!")
2. Write multiple rows
#!/usr/bin/env pythonfilename = 'programming.txt'with open(filename,'w') as file_object: file_object.write("I love programming!\n") file_object.write("yes!\n")
3. attach to a file
#!/usr/bin/env pythonfilename = 'pi'with open(filename,'a') as file_object: file_object.write("I love programming!\n") file_object.write("yes!\n")
Iii. Exceptions
1. Use try-try T code block
#!/usr/bin/env pythontry: print(5/0)except ZeroDivisionError: print("You cant divide by zero!")