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.
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.
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.
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.
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.
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 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.
for line in lines:
replace()replacement function
file.replace(‘dog’, ‘cat’)
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.
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.
The function write() will not automatically wrap the text after it is written, so you need to add the newline character\n yourself.
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.
os.path module contains many useful functions related to file names and file paths.
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.
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' |
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.
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.
Exception occurs when the divisor is 0.
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
|
Python’s built-in logging module can easily record error information.
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.
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.
json.dump and json.load are used in combination to store and load data respectively.
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.
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.
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!