Read data from file
This time I plan to adjust my thinking and attach the code written while learning according to the knowledge points. Let's see if it will be clearer.
#Open and read a file and display the contents on the screen with open('pi_digist.txt') as file_object: contents=file_object.read() print(contents)
The function of this part of code is to open a file called PI in the current executable directory_ Digist's text file reads out and outputs the contents of the file as a string.
The first line of code here contains a lot of content. The first is the open keyword, which is used to open a file and return an object representing the file, which is assigned to file_object, and the first with keyword is used to close the file when you don't need to access the file, which saves the step of closing (forgetting to close the file).
The second line of read is to output the contents of the file as a string.
Path to file
#Open and read a file and display the contents on the screen with open('text_file/pi_digist.txt') as file_object: contents=file_object.read() print(contents)
Here, we do an operation, that is, create a new folder in the executive file directory, and put PI_ Put the digist text in it, so that the previous code will not find the file, resulting in an error. At this time, the concept of file path is introduced. This concept has been mentioned in the learning of C. I won't say much here.
Read line by line
#Open and read a file line by line and display the content on the screen with open('text_file/pi_digist.txt') as file_object: for line in file_object: print(line)
Here, the line by line reading of the file is realized through the loop, so there is a feasible way to operate the text content.
Put the contents of the file into memory
#Open and read a file, save the contents of the file in a list, and use it after closing the file with open('text_file/pi_digist.txt') as file_object: lines=file_object.readlines() pi_string='' for line in lines: pi_string+=line.strip() print(line.rstrip()) print(pi_string) print(len(pi_string))
The object returned by open can only be used in the with code block, so we can save the object content in the list and operate outside the code block.
Super large file
#For large files, the case here is the Pi of one million bits with open('pi_million_digits.txt') as file_object: lines=file_object.readlines() pi_string='' for line in lines: pi_string+=line.strip() #To prevent the terminal display from exploding, only 50 digits after the decimal point are displayed. It can be seen that the file size has no impact on the operation print(f"{pi_string[:52]}...") print(len(pi_string))
Please attach the results here
3.14159265358979323846264338327950288419716939937510... 1000002
We can see that such an operation can be realized for files of any size as long as the system memory is enough.
Entertainment case, does PI have your birthday
#See if your birthday is in PI birthday=input("enter you birthday,in the form mmddyy:") if birthday in pi_string: print("you birthday appear in the first million digits of pi!") else: print("you birthday does not appear in the first million digits of pi!")
There's nothing to say about this. Just remember to use the input terminal.
write file
#Write file, here we create an empty text file programming in advance filename='programming.txt' with open(filename,'w') as file_object: file_object.write("i love programming!")
The write file here allows us to create a new one. In fact, if there is no one, the code will generate one by itself. However, it should be noted that if we open the file in write mode ('w ') and the file exists before, Python will empty the file content.
It should be noted here that Python can only write string data to text. If you want to enter a value, you must first convert it with the str keyword.
In addition, the write () function does not add a newline character. If you use the write function multiple times, multiple strings will be connected at the beginning and end. You need to add a newline character yourself
Attach to file
Sometimes, when we input content into a file, we need to keep the original content. At this time, we can use the additional mode ('a '), which will automatically point to the end of the file to add the content.
Specific cases are as follows:
filename='programming.txt' with open(filename,'w') as file_object: file_object.write("i love programming!\n") file_object.write("I like python\n") with open(filename,'a') as file_object: file_object.write("i love programming!\n") file_object.write("I like python")
The result is:
i love programming! I like python i love programming! I like python
If it is opened in write mode for the second time, there will only be the last two lines.
abnormal
Exceptions are used to manage some errors that the computer does not know how to deal with during program execution (probably that's what I thought when I studied C + +), and the simplest is the division of 0.
Exception use try_except code block. Tell the program what to do in this case.
#abnormal try: print(5/0) except ZeroDivisionError: print("you cannot divide by 0")
If you don't have this code block and simply output 5 / 0, the user will see traceback. In this way, the program can smoothly output the prepared error information.
(ps: the ZeroDivisionError is the name of this error. It does not affect the use, but if you write the wrong name, it will report an error.)
Flexible use of exceptions can prevent the program from crashing at any time, and ensure that the program runs first, so that the parts that can run later can not run.
#Specific use of exceptions print("give me 2 number,i will divide them") while True: first_number=input("first_number: ") if first_number=='q': break second_number=input("second_number: ") if second_number=='q': break try: answer=int(first_number)/int(second_number) except ZeroDivisionError: print("you cannot divide by 0") else: print(answer)
(specific use case of ZeroDivisionError)
Handling FileNotFoundError exception
When using a file, a common problem is that the file cannot be found. At this time, you can also use exceptions to handle it in a more intuitive way:
#File exception try: with open('alice.txt',encoding='utf-8') as f: contents=f.read() except FileNotFoundError: print("Not find the file")
Analyze text
Here, we added Alice in Wonderland to the executable file directory, named Alice, and then roughly judged the length of the text file through the code
filename='alice.txt' try: with open(filename,encoding='utf-8') as f: contents=f.read() except FileNotFoundError: print("Not find the file") else: #Calculate how many words there are in a large text words=contents.split() num_words=len(words) print(f"the file {filename} has about {num_words} words")
Here, we can also write this part as a function, and take the file path as a parameter to realize the use of multiple files.
Silent failure
The so-called silent failure means that when an exception occurs in the program, the program does not mean anything and the code continues to run. Here we use the pass keyword.
#File exception try: with open('alice.txt',encoding='utf-8') as f: contents=f.read() except FileNotFoundError: pass
Through exceptions, we can avoid the impact of uncontrollable situations such as user input and network connection on code operation.
Store data
Here we use the json module in the Python standard library. For the relevant information of the Python standard library, see Chapter 9 above.
Save data using json
#Save data using json import json numbers=[2,3,5,7,11,13] filename='numbers.json' with open(filename,'w') as f: #Store the list of numbers in the json file json.dump(numbers,f) #Reading data using json with open(filename) as f: numbers_2=json.load(f) print(numbers_2)
json is used to save the information so that the user information can be lost when the program stops running.
Large code summarizing the previous knowledge points (relative)
def get_stored_uesrname(): '''If the user name was previously stored, get it''' filename='username.json' try: with open(filename) as f: username=json.load(f) except FileNotFoundError: return None else: return username def get_new_username(): '''Enter a new user name''' username=input("what's your name: ") filename='username.json' with open(filename,'w') as f: json.dump(username,f) return username def greet_user(): '''Greet users''' username=get_stored_uesrname() if username: print(f"welcome back,{username}!") else: username=get_new_username() print(f"we will remember you when you come back,{username}") greet_user()
This code contains most of the contents of these two chapters, but the function is still a little weak. Willing colleagues can add some functions. This time, I wrote a little more. I feel that the more the content is in the future.