In addition to Weibo, there is also WeChat
Please pay attention
WeChat public account
Shulou
2025-01-18 Update From: SLTechnology News&Howtos shulou NAV: SLTechnology News&Howtos > Development >
Share
Shulou(Shulou.com)06/03 Report--
This article mainly explains "how to understand the file operation and exception module". The explanation in the article is simple and clear, and is easy to learn and understand. let's go deep into the editor's train of thought. Let's study and learn how to understand file operation and exception module.
File operation
Our program can read or write to a file. By default, files are opened in read mode ('r'), but can also be opened in write mode ('w') and append mode ('a').
Your program can read information from a file or write data to a file. Reading from a file allows you to process all kinds of information; writing to a file allows the user to start over the next time you run your program. You can write text to a file and store Python structures, such as lists, in a data file.
Read a file
To read from a file, the program needs to open the file and then read the contents of the file. You can read the entire contents of the file at once, or you can read the file line by line. The with statement ensures that when the program finishes accessing the file, the file is properly closed.
Read the whole file at once
Filename = 'siddhartha.txt' with open (filename) as f_obj: contents = f_obj.read () print (contents)
Read line by line
Each line read from the file has a newline character at the end of the line, and the print function adds its own newline character. The rstrip () method eliminates the extra blank lines that are generated when printing to the terminal.
Filename = 'siddhartha.txt' with open (filename) as f_obj: for line in f_obj: print (line.rstrip ())
Store rows in a list
Filename = 'siddhartha.txt' with open (filename) as f_obj: lines = f_obj.readlines () for line in lines: print (line.rstrip ())
Write to a file
Pass the'w' parameter to open () and tell Python that you want to write to the file. Caution: if the file already exists, this will delete the contents of the file.
Pass the'a 'parameter to tell Python that you want to add to the end of an existing file.
Write an empty file
Filename = 'programming.txt' with open (filename,' w') as f: f.write ("I love programming!")
Write multiple lines to an empty file
Filename = 'programming.txt' with open (filename,' w') as f: f.write ("I love programming!\ n") f.write ("I love creating new games.\ n")
Append write file
Filename = 'programming.txt' with open (filename,' a') as f: f.write ("I also love working with data.\ n") f.write ("I love making apps as well.\ n") file path
When Python runs the open () function, it looks for files in the same directory where the program being executed is stored. You can use relative paths to open files from subfolders. You can also use an absolute path to open any file in the system.
Open a file from a subfolder
F_path = "text_files/alice.txt" with open (f_path) as f_obj: lines = f_obj.readlines () for line in lines: print (line.rstrip ())
Open a file using an absolute path
F_path = "/ home/ehmatthes/books/alice.txt" with open (f_path) as f_obj: lines = f_obj.readlines ()
Open a file on Windows
Windows sometimes misinterprets forward slashes. If this is the case, use a backslash in the file path.
F_path = r "C:\ Users\ ehmatthes\ books\ alice.txt" with open (f_path) as f_obj: lines = f_obj.readlines () Except exception module
Exceptions are special objects that help programs respond to errors in an appropriate manner. For example, if a program tries to open a file that does not exist, you can use an exception to display an informative error message instead of crashing the program.
Place the code that may cause the error in the try block. The code that should be run in response to the error is in the except block. Code that should be run only if the try block is successful is put into the else block.
Prompt = "How many tickets do you need?" Num_tickets = input (prompt) try: num_tickets = int (num_tickets) except ValueError: print ("Please try again.") Else: print ("Your tickets are printing.")
Try-except code block
Handling ZeroDivisionError exceptions
Try: print (5amp 0) except ZeroDivisionError: print ("You can't divide by zero!")
Handling FileNotFoundError exceptions
F_name = 'siddhartha.txt' try: with open (f_name) as f_obj: lines = f_obj.readlines () except FileNotFoundError: msg = "Can't find file {0}." .format (f_name) print (msg)
When writing code, it is difficult to know what kind of exception to handle. Try to write code without a try block and have it generate an error. Backtracking will tell you what kind of exception the program needs to handle.
Else code block
The try block should contain only code that may cause an error. Any code that depends on the successful execution of the try block should be placed in the else block.
Use else blocks
Print ("Enter two numbers. I'll divide them.") X = input ("First number:") y = input ("Second number:") try: result = int (x) / int (y) except ZeroDivisionError: print ("You can't divide by zero!") Else: print (result)
Prevent crashes caused by user input
If there is no except block in the following example, if the user tries to divide by zero, the program will crash. As written, it will handle errors gracefully and continue to run.
# A simple division calculator. Print ("Enter two numbers. I'll divide them.") Print ("Enter 'q' to quit.") While True: X = input ("\ nFirst number:") if x = 'q': break y = input ("Second number:") if y =' q': break try: result = int (x) / int (y) except ZeroDivisionError: print ("You can't divide by zero!") Else: print (result)
Fail silently
Sometimes you want the program to continue running when it encounters an error without reporting the error to the user. You can do this by using the pass statement in the else block.
Use the pass statement in an else block
F_names = ['alice.txt',' siddhartha.txt', 'moby_dick.txt',' little_women.txt'] for f_name in f_names: # reports the length of each file found. Try: with open (f_name) as f_obj: lines = f_obj.readlines () except FileNotFoundError: # move on to the next file. Pass else: num_lines = len (lines) msg = "{0} has {1} lines." .format (f_name, num_lines) print (msg)
Avoid empty except blocks
Exception handling code should catch specific exceptions that are expected to occur during program execution. An empty except block will catch all exceptions, including keyboard interruptions and system exits that may be required when the program is forced to close.
If you want to use try blocks but are not sure which exception to catch, use exception. It catches most exceptions, but still allows you to deliberately interrupt the program.
Avoid empty except blocks
Try: # Do something except: pass
Use Exception
Try: # Do something except Exception: pass
Print exception
Try: # Do something except Exception as e: print (e, type (e))
Using json to store data
The json module allows you to dump simple Python data structures into a file and load data from that file the next time the program runs. The JSON data format is not specific to Python, so you can also share this kind of data with people who use other languages.
When working with stored data, it is important to understand how to manage exceptions. Before working with data, you usually want to make sure that the data you are trying to load exists.
Use json.dump () to store data
# store some numbers. Import json numbers = [2,3,5,7,11,13] filename = 'numbers.json' with open (filename,' w') as f_obj: json.dump (numbers, f_obj)
Use json.load () to store data
# load some previously stored numbers. Import json filename = 'numbers.json' with open (filename) as f_obj: numbers = json.load (f_obj) print (numbers)
Ensure that the stored data exists
Import json f_name = 'numbers.json' try: with open (f_name) as f_obj: numbers = json.load (f_obj) except FileNotFoundError: msg = "Can't find {0}." .format (f_name) print (msg) else: print (numbers)
Decide which errors to report
Well-written, properly tested code is less prone to internal errors, such as syntax or logic errors. However, it is possible to throw an exception whenever your program relies on external factors such as user input or the existence of files.
Thank you for your reading, the above is the content of "how to understand the file operation and exception module". After the study of this article, I believe you have a deeper understanding of how to understand the file operation and exception module. The specific use of the situation also needs to be verified by practice. Here is, the editor will push for you more related knowledge points of the article, welcome to follow!
Welcome to subscribe "Shulou Technology Information " to get latest news, interesting things and hot topics in the IT industry, and controls the hottest and latest Internet news, technology news and IT industry trends.
Views: 0
*The comments in the above article only represent the author's personal views and do not represent the views and positions of this website. If you have more insights, please feel free to contribute and share.
Continue with the installation of the previous hadoop.First, install zookooper1. Decompress zookoope
"Every 5-10 years, there's a rare product, a really special, very unusual product that's the most un
© 2024 shulou.com SLNews company. All rights reserved.