Python file read/write and Exception Code example,

Source: Internet
Author: User

Python file read/write and Exception Code example,

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 python try:  print(5/0)except ZeroDivisionError:  print("You cant divide by zero!")

This section describes the exception content.

Python exception handling

Python provides two very important functions to handle exceptions and errors in the running of python programs. You can use this function to debug python programs.

What is an exception?

An exception is an event that occurs during program execution and affects normal execution of the program.

Generally, an exception occurs when Python cannot process the program normally.

An exception is a Python object, indicating an error.

When a Python script exception occurs, we need to capture and process it; otherwise, the program will terminate the execution.

Exception Handling

You can use the try/try t statement to catch exceptions.

The try/try t statement is used to detect errors in the try statement block, so that the try t statement can capture and handle exceptions.

If you don't want to end your program when an exception occurs, just capture it in try.

Syntax:

The following is a simple try... example t... else Syntax:

Try: <Statement> # Run another code except T <name>: <Statement> # If 'name' exception occurs in try <name>, <DATA>: <Statement> # If a 'name' exception is thrown, obtain the additional data else: <Statement> # If no exception occurs

The working principle of try is that after a try statement is started, python marks the context of the current program, so that when an exception occurs, you can return here and the try clause executes first, what will happen next depends on whether exceptions occur during execution.

If an exception occurs during statement execution after try, python will jump back to try and execute the First alias t clause that matches the exception. The Exception Processing is complete, the control flow uses the entire try Statement (unless a new exception is thrown when an exception is handled ).

If an exception occurs in the statement after try, but there is no matching limit t clause, the exception will be submitted to the try at the upper layer or to the upper layer of the Program (this will end the program, and print the default error information ).

If no exception occurs during the execution of the try clause, python will execute the statement after the else Statement (if else exists) and then control the flow through the entire try statement.

Instance

The following is a simple example. It opens a file and writes content to the file without exception:

#! /Usr/bin/python #-*-coding: UTF-8-*-try: fh = open ("testfile", "w") fh. write ("this is a test file for testing exceptions !! ") Failed t IOError: print" Error: failed to find the file or failed to read the file "else: print" the content is written to the file successfully "fh. close ()

Output results of the above program:

$ Python test. py content successfully written to the file $ cat testfile # view the written content. This is a test file for testing exceptions !!

Instance

The following is a simple example. It opens a file and writes content to the file. However, the file has no write permission and an exception occurs:

#! /Usr/bin/python #-*-coding: UTF-8-*-try: fh = open ("testfile", "w") fh. write ("this is a test file for testing exceptions !! ") Failed t IOError: print" Error: failed to find the file or failed to read the file "else: print" the content is written to the file successfully "fh. close ()

To facilitate the test, we can remove the write permission of the testfile file before executing the code. The command is as follows:

chmod -w testfile

Then execute the above Code:

$ Python test. py Error: No file found or an Error occurred while reading the file.

Well, I 'd like to introduce so much. There are many articles on Python exceptions on this site. For more information, see.

The above is all the content about reading, writing, and Exception Code examples of Python files. I hope it will be helpful to you. If you are interested, you can continue to refer to this site: enumerate function code parsing in Python, Python network programming details, python data type determining the difference between type and isinstance instance parsing, etc, if you have any questions, please feel free to leave a message. Thank you!

Related Article

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.