Python Basic Learning Summary (eight)

Source: Internet
Author: User
Tags configuration settings

10. Files and exceptions

Learn to process files, allow the program to quickly analyze large amounts of data, learn to deal with errors, avoid the program in the face of unexpected crashes. Learning exceptions, which are special objects created by Python, are used to manage errors that occur when the program is running, improving the applicability, usability, and stability of the program.

The Learning module Json,json can be used to save user data and prevent the program from accidentally being lost when it stops running.

Learn to process files and save data, you can make the program easier to use, the user can choose what type of data to enter, and choose when to enter, and can use the program to process some after the shutdown program, the next time continue to do.

Learn to handle exceptions, help deal with situations where files are not present, and handle various problems that might cause the program to crash, making the program more robust in the face of various errors, whether they originate from an unconscious error or a malicious attempt to sabotage a program.

10.1 reading data from a file

Reading a file can read the entire file at once, or it can read the file row by line. Depending on the size of the file, choose the Read method yourself.

10.1.1 reading the entire file

In Python, there are 3 steps to read and write a file:

1. Call the open () function to return a File object.

2. Invokes the read () or write () method of the File object.

3. Call the Close () method of the file object to close it.

Opening a file with the open () function

with open (filename) as File_object:

Contents = File_object.read () #不用调用关闭方法, with auto-close file.

Looks for the file to open in the current directory of the file.

Read () method reads file contents

The read () method of the File object:

>>> hellocontent = Hellofile.read ()

>>> hellocontent

' Hello world! '

You can use the ReadLines () method to get a list of strings from the file. Each string in the list is each line in the text.

10.1.2 File path

Notice the slash, the backslash on Windows, and the forward slash on OS X and Linux.

With open (' Text_files\filename.txt ') as File_object.

There are two ways of specifying a file path.

    • Absolute path, always starting from the root folder.
    • Relative path, which is relative to the current working directory of the program.

Absolute file path

 Win:

File_path = ' C:\Users\ehmatthes\other_files\text_files\filename.txt '

With open (File_path) as File_object:

 Linux and OS:

File_path = '/home/ehmatthes/other_files/text_files/filename.txt '

With open (File_path) as File_object:

Also a little (.) and Dot (..) Folder They are not real folders, but special names that can be used in paths. When a single period ("point") is used as the folder name, it is the abbreviation for "This directory". A two period ("dot") means the parent folder.

 Working with absolute and relative paths

The 1.os.path module provides functions that return an absolute path to a relative path and check whether a given path is an absolute path.

2. Call Os.path.abspath (path) to return the string for the absolute path of the parameter. This is an easy way to convert a relative path to an absolute path.

3. Call Os.path.isabs (path), returns True if the argument is an absolute path, or False if the argument is a relative path.

4. Calling Os.path.relpath (path, start) returns a string from the start path to the path's relative paths.

5. If start is not provided, the current working directory is used as the start path.

10.1.3 reading file data row by line

For line in lines:

  Replace () Replacement function

File.replace (' dog ', ' cat ')

10.2 Writing Files

10.2.1 writing an empty file

Open (' File ', ' W ') provides two arguments, file names and operations

1. Read mode ' R '

2. Write mode ' W '

3. Additional mode ' a '

4. Read and write mode ' r+ '

5. If you omit the schema argument, Python will only open the file in the default read-only mode.

6. If the file does not exist, open will automatically generate the file.

7. Inputs are input and outputs are output, so we refer to the input and output collectively as input/output, or abbreviated to IO.

8. When entering a password, if you want to be invisible, you need to take advantage of the Getpass method in the Getpass module.

Note that if the file is already present, the file will be emptied if it is opened in write mode ' W '.

If the file name passed to open () does not exist, write mode and add mode will create a new empty file . After the file is read or written , the Close () method is called before the file can be opened again.

Python can only write strings to a text file, and to store numeric data into a text file, it needs to be converted to a string format using the function str.

>>> baconfile = open (' Bacon.txt ', ' W ')

>>> baconfile.write (' Hello world!\n ')

13

>>> Baconfile.close ()

>>> baconfile = open (' Bacon.txt ', ' a ')

>>> baconfile.write (' Bacon is not a vegetable. ')

25

>>> Baconfile.close ()

>>> baconfile = open (' Bacon.txt ')

>>> content = Baconfile.read ()

>>> Baconfile.close ()

>>> Print (content)

Hello world! Bacon is not a vegetable.

First, we open bacon.txt in write mode. Because there is no bacon.txt,python to create one. Call Write () on the open file, and pass the string argument to write () ' Hello world! \ n ', writes a string to the file and returns the number of characters written, including the newline character. Then close the file.

To add text to the contents of the file, instead of replacing the string we just wrote, we open the file in Add mode. Write to the file ' Bacon is not a vegetable. ', and close it. Finally, in order to print the contents of the file to the screen, we open the file in the default read mode, call Read (), save the resulting content in the content, close the file, and print the content.

Note that the write () method does not automatically add a newline character to the end of a string, as in the print () function. You must add the character yourself.

Saving variables with the shelve module

With the shelve module, you can save variables in a Python program to a binary shelf file. This allows the program to recover variable data from the hard disk. The shelve module allows you to add "save" and "open" functions to your program. For example, if you run a program and enter some configuration settings, you can save these settings to a shelf file, and then have the program load them the next time you run it.

>>> Import Shelve

>>> shelffile = Shelve.open (' MyData ')

>>> cats = [' Zophie ', ' Pooka ', ' Simon ']

>>> shelffile[' cats '] = cats

>>> Shelffile.close ()

Run the previous code on Windows and you'll see 3 new files in the current working directory: Mydata.bak, Mydata.dat, and Mydata.dir. On OS X, only one mydata.db file is created.

These binaries contain the data stored in the shelf. The format of these binaries is not important, you just need to know what the shelve module does, without knowing how it is done. This module lets you not worry about how to save your program's data to a file. Your program can later use the shelve module to reopen the files and retrieve the data. The shelf values do not have to be opened in read or write mode because they are both readable and writable when they are opened.

>>> shelffile = Shelve.open (' MyData ')

>>> type (shelffile)

<class ' shelve. Dbfilenameshelf ' >

>>> shelffile[' Cats ' [' Zophie ', ' Pooka ', ' Simon ']

>>> Shelffile.close ()

Just like a dictionary, the shelf value has the keys () and the values () method, which returns a value similar to the list of keys and values in shelf. Because these methods return a list-like value rather than a real list, they should be passed to the list () function, in the form of a listing.

>>> shelffile = Shelve.open (' MyData ')

>>> list (Shelffile.keys ())

[' Cats ']

>>> list (shelffile.values ())

[[' Zophie ', ' Pooka ', ' Simon ']

>>> Shelffile.close ()

When creating files, plain text is useful if you need to read them in a text editor such as Notepad or TextEdit. However, if you want to save data from a Python program, use the shelve module.

10.2.2 Writing Multiple lines

The function write () does not wrap the text after it is written, and you need to add a newline character \ n.

10.3 OS operation

10.3.1 creating a new folder with Os.makedirs ()

The program can create a new folder (directory) with the Os.makedirs () function.

>>> Import OS

>>> os.makedirs (' C:\\delicious\\walnut\\waffles ')

This will not only create the C:\delicious folder, but also create the Walnut folder under C:\delicious and create waffles folders in C:\delicious\walnut. That is, os.makedirs () will create all the necessary intermediate folders in order to ensure that the full path name exists.

10.3.2 Os.path Module

The Os.path module contains many useful functions related to filenames and file paths.

1. View file size and folder contents

    • Once you have a way to process the file path, you can start collecting information for specific files and folders. The Os.path module provides functions to view the number of bytes in a file and the files and subfolders in a given folder.
    • The call to Os.path.getsize (path) returns the number of bytes of the file in the path parameter.
    • Calling Os.listdir (path) Returns a list of file name strings, including each file in the path parameter (note that this function is in the OS module, not os.path).
    • Os.path.join () is used to connect the folder name and the current file name.

2. Check the path validity

    • If you provide a path that does not exist, many Python functions will crash and error. The Os.path module provides functions to detect the existence of a given path and whether it is a file or a folder.
    • If the file or folder that the path parameter refers to exists, calling os.path.exists (path) returns TRUE, otherwise False is returned.
    • If the path parameter exists and is a file, calling Os.path.isfile (path) returns TRUE, otherwise False is returned.
    • If the path parameter exists and is a folder, calling Os.path.isdir (path) returns TRUE, otherwise False is returned.

10.4 Organization Documents

10.4.1 Shutil Module

The Shutil (or shell tool) module contains functions that let you copy, move, rename, and delete files in a Python program. To use Shutil functions, you first need the import shutil.

10.4.1.1 Copying files and folders

The Shutil module provides functions for copying files and entire folders.

1. Call Shutil.copy (source, destination) to copy the file at source at the path to the folder at the path destination (source and destination are strings).

2. If destination is a file name, it will be the new name of the copied file. The function returns a string that represents the path to the copied file.

>>> import Shutil, OS

>>> os.chdir (' c:\\ ')

>>> shutil.copy (' c:\\spam.txt ', ' c:\\delicious ')

' C:\\delicious\\spam.txt '

>>> shutil.copy (' eggs.txt ', ' c:\\delicious\\eggs2.txt ')

' C:\\delicious\\eggs2.txt '

10.4.1.2 file and folder movement and renaming

Call Shutil.move (source, destination), move the folder of the path source to the path destination, and return the string to the absolute path of the new location.

If destination points to a folder, the source file is moved to destination and the original file name is maintained.

10.5 Exceptions

Python uses special objects called exceptions to manage errors that occur while the program is running.

An exception is created whenever a Python error occurs at a loss.

If you write an exception, the program will continue, or the program will stop and return trackback with reports about the exception.

Exceptions are handled using try-except code blocks . Executes the specified action and tells Python how to change it. With the try-except code block , even if the program encounters an error, it will continue to run, displaying its own friendly error prompts to let the user know what is wrong.

1.ZeroDivisionError exception

The divisor is 0 o'clock, and the exception occurs.

2.TypeError exception

only integers and floating-point type parameters are allowed. Data type checking can be implemented with built-in function isinstance ()

def my_abs (x):

If not isinstance (x, (int, float)):

Raise TypeError (' bad operand type ')

If x >= 0:

return x

Else

Return-x

ValueError exception

3. Logging Errors

Python's built-in logging module makes it very easy to log error messages.

4. Throwing errors

If you want to throw an error, you can first define an incorrect class, choose a good inheritance relationship, and then throw an instance of the error with the raise statement, as needed.

10.6 Storing data

Use a JSON module to store data. The format of JSON data is not Python-specific and can be shared with people in other programming languages. is a lightweight format that is useful and easy to learn.

The JSON (JavaScript Object Notation) format was originally developed for JavaScript, but then became a common format that was used in many languages.

Using Json.dump () and Json.load ()

Json.dump () accepts two arguments, the data to be stored, and the file objects that can be used to store the data.

    1. Program that stores a set of numbers json.dump ()
    2. program that reads a number into memory json.load ()

10.6.2 Saving and reading user-generated data

Json.dump and Json.load are used in conjunction, respectively, to store and load data.

10.6.3 Re-construction

1. The code works correctly, but it can be further improved by dividing the code into a series of functions that do the work. Such a process is called refactoring. Refactoring makes code clearer, easier to understand, and easier to scale.

2. Place most of the logic within one or more functions.

10.6.4 Summary

1. Learn to read the file, the entire file read and a line read, operation file, open, read mode, write mode, additional mode, read write mode.

2. How to use the Try-except-else code block for exception handling. The exception type. Manipulate data, save and read data, use of JSON modules, use of dump and load, learn to refactor code.

10.7 Commissioning

1. Assertions

Any place that uses print () to assist in viewing can be replaced with an assertion (assert).

def foo (s):

n = Int (s)

Assert n! = 0, ' n is zero! '

Return 10/n

def main ():

Foo (' 0 ')

The assert means that the expression n! = 0 should be true, otherwise, depending on the logic that the program runs, the subsequent code will definitely go wrong.

If the assertion fails, the Assert statement itself throws Assertionerror.

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.