Python programming from entry to practice _ Chapter 10 _ files and exceptions,
Read the entire file
File pi_digits.txt
Ghost file pi_digits.txt 3.1415926535 8979323846 2643383279
The following program opens and reads the entire file, and then displays its content on the screen:
With open ("pi_digits.txt") as fileobject: contents = fileobject. read () print (contents) # running result 3.1415926535 8979323846 2643383279
Open the file with the function open (). The function open (0 accepts the name parameter of the file to be opened, and python searches for the specified file in the directory of the file currently executed. The open () function returns an object that represents a file. Then, save the object in the variable used later, which can be a file handle. Keyword with is disabled after you do not need to access the file. In this program, we do not use close () to close the file. You can also do this. However, if the program has a bug, the close () statement is not executed, and the file will not be closed. With the object that represents the pi_digits file, we can use the read () method to read the content and store it as a long string in the variable contents.
File Path
Relative Path: Path of the current directory
In linux:
with open('text_files/filename.txt') as file_object:
Windows:
with open('text_files\filename.txt') as file_object:
Absolute path: relative to the root directory
In linux:
file_path = '/home/ehmatthes/other_files/text_files/filename.txt'with open(file_path) as file_object:
Windows:
file_path = 'C:\Users\ehmatthes\other_files\text_files\filename.txt'with open(file_path) as file_object:
Create a list containing the content of each row of the file
When reading files, they are often read row by row;
The readlines () method reads each row from the file and stores it in a list;
Filename = 'pi_digits.txt 'with open (filename) as file_object: lines = file_object.readlines () print (lines) for line in lines: print (line. rstrip () # running result ['3. 1415926535 \ n', '2014 \ n', '2014 \ n'] 8979323846 2643383279 3.1415926535
Write Empty files
filename = 'programming.txt'with open(filename, 'w') as file_object: file_object.write("I love programming.\n")
Running result:
If the file exists, write is overwritten. If the file does not exist, write is created.
I love programming.
In this example, two real parameters are provided when open () is called (see section Ø ). The first real parameter is the name of the file to be opened. The second real parameter ('W') tells Python that we want to open the file in write mode. When opening a file, you can specify the Read mode ('R'), write mode ('W'), and additional mode ('A ') or enable you to read and write files ('R + '). If you omit the mode arguments, Python will open the file in the default read-only mode.
Attach to file
filename = 'programming.txt'with open(filename,'a') as file_object: file_object.write("I also love python!\n") file_object.write("I love creating apps\n")
# Running result
Add
I love programming.I also love python!I love creating apps
To handle exceptions, first look at a simple exception:
Print (5/0) # Run the result Traceback (most recent call last): File "D:/python_cd/Python programming from getting started to practice/division. py ", line 1, in <module> print (5/0) ZeroDivisionError: division by zero
Obviously, python cannot do this, so you will see a traceback. The error ZeroDivisionError is an exception object, so that python will stop running the program, next we will tell python what to do when such an error occurs, instead of terminating the program and returning an error.
Try: print (5/0) failed t: print ("You can't divide by zero! ") # Run the result You can't divide by zero!
In this example, the code in the try code block raises the ZeroDivisionError exception. Therefore, Python points out how to solve the issue by running the code in the code block. In this way, the user can see a friendly error message instead of traceback.
Else code block
Print ("Give me two numbers, and I'll divide them. ") print (" Enter 'q' to quit. ") while True: first_number = input (" \ nFirst number: ") if first_number = 'q': break second_number = input (" Second number: ") try: answer = int (first_number)/int (second_number) limit t ZeroDivisionError: print ("You can't divide by 0! ") Else: print (answer) # Run the result Give me two numbers, and I'll divide them. enter 'q' to quit. first number: 12 Second number: 62.0 First number: 12 Second number: 0You can't divide by 0!
The try-try t-else code block works as follows: Python tries to execute the code in the try code block. Only code that may cause exceptions must be placed in the try statement. Sometimes there are some codes that need to be run only when the try code block is successfully executed; these codes should be placed in the else code block. The compile T code block tells Python what to do if it raises a specified exception when trying to run the code in the try code block. There is a pass statement in python, which can be used in the code block to prevent python from doing so. For example, if only pass is added under the limit t statement, it indicates that no error is returned.
Many programs in the JSON module require users to enter certain information, such as allowing users to store game preferences or provide data to be visualized. No matter what you focus on, the program stores the information provided by users in data structures such as lists and dictionaries. When you close a program, you almost always need to save the information they provide. A simple way is to use module json to store data.
Module json allows you to dump a simple Python data structure to a file and load the data in the file when the program runs again. You can also use json to share data between Python programs. More importantly, the JSON data format is not specific to Python, which allows you to share data stored in JSON format with people in other programming languages. This is a lightweight format that is useful and easy to learn.
Json. dumps
import json info={'name':'Tom', 'age':'12', 'job':'work',} f=open('file1.txt','w') f.write(json.dumps(info)) f.close()
Json. loads
import json f=open('file1.txt','r') data=json.loads(f.read()) f.close() print(data) print(data['name'])