Home > Backend Development > Python Tutorial > Python basic learning summary (8)

Python basic learning summary (8)

PHP中文网
Release: 2017-07-14 18:13:14
Original
1541 people have browsed it

10. Files and exceptions

Learn to process files, let the program quickly analyze large amounts of data, learn to handle errors, and avoid the program from crashing in the face of accidents. Learn about exceptions. Exceptions are special objects created by python. They are used to manage errors that occur when a program is running and improve the applicability, usability, and stability of the program.

Learning module json, json can be used to save user data to avoid loss when the program stops running unexpectedly.

Learning to process files and save data can make the program easier to use. Users can choose what type of data to input and when to input it. They can also close the program after using the program to process something and continue working on it next time. .

Learn to handle exceptions to help deal with file non-existence situations, as well as handle various problems that may crash the program, making the program more robust in the face of various errors, whether these erroneous data originate from unintentional errors or from Malicious attempts to corrupt a program.

10.1 Reading data from a file

 Reading a file can read the entire file at once or read the file line by line. Choose your own reading method depending on the size of the file.

10.1.1Read the entire file

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

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

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

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

Use the open() function to open the file

 with open(file name) as file_object:

            contents = file_object.read() # No need to call the closing method, with automatically closes the file.

Will search for the file to open in the current directory of the file.

The read() method reads the file content

 File object’s read() method:

>>> 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 of text.

10.1.2 File path

Note the slashes, backslashes on Windows, and forward slashes on OS X and Linux.

 with open('text_files\filename.txt') as file_object.

There are two ways to specify a file path.

  • "Absolute path" always starts 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:

There are also dot (.) and dot (..) folders. They are not real folders, but special names that can be used in paths. A single period ("dot"), when used as a folder name, is the abbreviation for "this directory." The two periods ("dots") mean the parent folder.

  Handling absolute paths and relative paths

 1.os.path module provides some functions that return the absolute path of a relative path and check whether the given path is an absolute path.

 2. Calling os.path.abspath(path) will return the string of 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). If the parameter is an absolute path, it returns True. If the parameter is a relative path, it returns False.

 4. Calling os.path.relpath(path, start) will return the string of the relative path from the start path to path.

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

10.1.3 Read file data line 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 actual parameters, file name and operation

 1.Reading mode ’r’

 2. Writing mode ‘w’

 3.Additional mode ‘a’

 4. Reading and writing mode ‘r+’

 5. If the mode parameter is omitted, python will only open the file in read-only mode by default.

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

 7. The input is Input and the output is Output. Therefore, we collectively refer to input and output as Input/Output, or abbreviated as IO.

 8. When entering the password, if you want it to be invisible, you need to use the getpass method in the getpass module.

Note, If opened in write mode ‘w’, if the file already exists, the file will be cleared.

If the file name passed to open() does not exist, both write mode and add mode will create a new empty file . After reading or writing a file , call the close() method before the file can be opened again.

 Python can only write strings into text files. To store numerical data into a text file, you need to use the function str to convert it into a string format.

>>> 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. Since bacon.txt doesn't exist yet, Python creates one. Call write() on the open file and pass the string parameter 'Hello world! \n' to write(), write the string to the file, and return the number of characters written, including newlines. Then close the file.

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

Please note that the write() method does not automatically add a newline character at the end of the string like the print() function does. You must add this character yourself.

Use shelve module to save variables

Using the shelve module, you can save variables in a Python program into a binary shelf file. In this way, the program can recover the data of the variables from the hard disk. The shelve module lets you add "save" and "open" functionality to your program. For example, if you run a program and enter some configuration settings, you can save those settings to a shelf file and have the program load them the next time it is run.

>>> import shelve

>>> shelfFile = shelve.open('mydata')

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

>>> shelfFile['cats'] = cats

>>> shelfFile.close()

Running the previous code on Windows, you will 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 binary files contain the data stored in the shelf. The format of these binaries doesn't matter, you just need to know what the shelve module does, not how it does it. This module takes the worry out of saving your program's data to a file. Your program can later use the shelve module to reopen these files and retrieve the data. Shelf values ​​do not have to be opened in read or write mode because they can be read or written once opened.

>>> shelfFile = shelve.open('mydata')

>>> type(shelfFile)

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

>>> shelfFile.close()

Just like a dictionary, shelf values ​​have keys() and values() methods, which return a list-like value of the keys and values ​​in the shelf. Because these methods return list-like values ​​rather than actual lists, they should be passed to the list() function to obtain list form.

>>> 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 like 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() will not automatically wrap the text after it is written, so you need to add the newline character\n yourself.

10.3 OS Operation

10.3.1 Use os.makedirs() to create a new folder

 Programs can use the os.makedirs() function to create new folders (directories).

>>> 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 the waffles folder under C:\delicious\walnut. That is, os.makedirs() will create all necessary intermediate folders in order to ensure that full pathnames exist.

10.3.2 os.path module

 os.path module contains many useful functions related to file names and file paths.

 1. View file size and folder contents

  • Once you have a way to handle file paths, you can start collecting information about specific files and folders. The os.path module provides functions for viewing the byte count of a file and the files and subfolders within a given folder.
  • Calling os.path.getsize(path) will return the number of bytes of the file in the path parameter.
  • Calling os.listdir(path) will return a list of filename strings, containing each file in the path parameter (note that this function is in the os module, not os.path).
  • Use os.path.join() to connect the folder name and the current file name.

 2. Check path validity

  • If the path you provide does not exist, many Python functions will crash and report an error. The os.path module provides functions for detecting whether a given path exists and whether it is a file or a folder.
  • If the file or folder pointed to by the path parameter exists, calling os.path.exists(path) will return True, otherwise it will return False.
  • If the path parameter exists and is a file, calling os.path.isfile(path) will return True, otherwise it will return False.
  • If the path parameter exists and is a folder, calling os.path.isdir(path) will return True, otherwise it will return False.

10.4 Organizational files

10.4.1 shutil module

The shutil (or shell tool) module contains functions that allow you to copy, move, rename, and delete files in Python programs. To use shutil functions, you first need to import shutil.

10.4.1.1 Copy files and folders

The shutil module provides some functions for copying files and entire folders.

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

 2. If destination is a file name, it will be used as the new name of the copied file. This function returns a string representing the path of the file being copied.

>>> 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 Moving and renaming files and folders

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

If destination points to a folder, the source file will be moved to destination and the original file name will be kept.

10.5 Exception

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

Whenever an error occurs in python, an exception is created.

If written to handle exceptions, the program will continue, otherwise the program will stop and return a trackback containing a report about the exception.

Exceptions are handled using the try-except code block. Perform the specified operation and tell python what to do. Using the try-except code block, even if the program encounters an error, it will continue to run and display a friendly error message written by you to let the user know what went wrong.

1.ZeroDivisionError exception

Exception occurs when the divisor is 0.

2.TypeError exception

Only integer and floating point type parameters are allowed. Data type checking can be implemented using the 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. Record errors

 Python’s built-in logging module can easily record error information.

4.Throw an error

If you want to throw an error, you can first define an error class as needed, select the inheritance relationship, and then use the raise statement to throw an error instance.

10.6 Storing data

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

The JSON (JavaScript Object Notation) format was originally developed for JavaScript, but has since become a common format used in many languages.

Use json.dump() and json.load()

 json.dump() accepts two actual parameters, the data to be stored and the file object that can be used to store the data.

  1. Program to store a set of numbers json.dump()
  2. Program to read numbers into memory json.load()

10.6.2 Saving and reading user-generated data

 json.dump and json.load are used in combination to store and load data respectively.

10.6.3 Refactoring

 1. The code runs correctly, but further improvements can be made - divide the code into a series of functions that complete specific work. This process is called reconstruction. Refactoring makes code clearer, easier to understand, and easier to extend.

 2. Put most of the logic into one or more functions.

10.6.4 Summary

 1. Learned to read files, read the entire file and read one line, operate files, open, read mode, write mode, append mode, read plus write mode.

 2. How to use the try-except-else code block for exception handling. Exception type. Manipulate data, save and read data, use json module, use dump and load, learn to refactor code.

10.7 Debugging

1. Assertion

Anywhere print() is used to assist viewing, assertion can be used instead.

def foo(s):

n = int(s)

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

return 10 / n

def main():

foo('0')

The meaning of assert is that the expression n != 0 should be True. Otherwise, according to the logic of program operation, the following code will definitely go wrong.

If the assertion fails, the assert statement itself will throw AssertionError.

The above is the detailed content of Python basic learning summary (8). For more information, please follow other related articles on the PHP Chinese website!

Related labels:
source:php.cn
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Latest Articles by Author
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template