Python files and exceptions,

Source: Internet
Author: User

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!")

 

Contact Us

The content source of this page is from Internet, which doesn't represent Alibaba Cloud's opinion; products and services mentioned on that page don't have any relationship with Alibaba Cloud. If the content of the page makes you feel confusing, please write us an email, we will handle the problem within 5 days after receiving your email.

If you find any instances of plagiarism from the community, please send an email to: info-contact@alibabacloud.com and provide relevant evidence. A staff member will contact you within 5 working days.

A Free Trial That Lets You Build Big!

Start building with 50+ products and up to 12 months usage for Elastic Compute Service

  • Sales Support

    1 on 1 presale consultation

  • After-Sales Support

    24/7 Technical Support 6 Free Tickets per Quarter Faster Response

  • Alibaba Cloud offers highly flexible support services tailored to meet your exact needs.