No offense to the title, but I thought the AD was fun. The mind map above, if you like, you can take it with you
Okay, cut to the chase
The article directories
-
- preface
- Your golden cudgel has arrived, please sign for it
- File to read and write
-
- Computer code table
- Read the file
-
- Step 1: Open the file
-
- Absolute path and relative path note points
- Step 2: Read the file
-
- The join () function
- Step 3: Close the file
- Written to the file
- Little practice
- My code
- I drew a circle to welcome you to this circle
preface
This series of articles assumes that you have some basic knowledge of C or C++, because I started Python after learning a little C++. Thank you qi Feng for your support. Also want to thank everyone’s support, the first two visits, collections, likes, comments are “condescending”, thank you, and friends can’t wait to wait for the third, really touched, although I write slowly, but at night less play two games can also improve the update speed.
By default, you will be accessing Baidu for this series of articles. And then, the contents of this series, to be honest, I personally prefer those two Primer Plus, so I will follow their directory structure. This series will also focus on cultivating your ability to do things on your own. After all, I cannot tell you all the knowledge points, so the ability to solve your needs by yourself is particularly important. Therefore, please do not regard the holes I have buried in the article as holes.Copy the code
Your golden cudgel has arrived, please sign for it
Today we’re going to talk about one of the most important aspects of Python, and one of the most important reasons for Python’s rise. Have you ever wondered, in this era of programming languages flying everywhere, there are old players C/C++, front-end PHP, H5, new Java, mathematics with MATLAB and R, why Python stands out?
Yes, because Python is a universal thing! It can call all kinds of packages to work for it, packages have all kinds of functions in them, so let’s say I’m going to use Python to process a bunch of Excel spreadsheets, do I have to write my own table-handling functions? No, it is too troublesome to write by yourself. Why not stand on the shoulders of giants? There’s a package called ‘CSV’ that does just that, so I’ll just call it over.
You can use Python to batch process tables, do simple face recognition, and do small projects. How are you, are you so excited?!
All right, take your time. Take your time. Here, you need to have a decent compiler, be it VS (py enabled), PyCharm, or whatever. I used PyCharm, VS is too big to open. Before downloading PyCharm, you need to download a Python. This is 2020-10-19. The latest version is 3.9.0. The latest versions of these two things are recommended on their official websites, and it is very convenient to install them. Basically, it is next, but it is not recommended to install them on DISK C.
Let’s move!!
Then, this and the next installment will take you through manipulating files in Python and manipulating Excel.
File to read and write
Functions and classes end, naturally also is the file read and write flow. For a while after learning database, I thought file reading and writing was useless, who still uses files these days, but I was wrong.
Computer code table
Let’s start with a computer code table:
Code table | applicability | The characteristics of |
---|---|---|
ASCII | English uppercase and lowercase characters are not supported | An American invention that takes up little space |
GB2312 code, GBK code | Support for Chinese | GBK code is an upgrade of GB2312 |
Unicode code | Support for international languages | Large space, strong applicability. |
Utf-8 code | Support for international languages | Conversion, small footprint. ASCII code is contained by UTF- -8 code |
File read and write, the main function of Python code to call computer files, can be used to read and write text records, audio clips, Excel documents, save mail, and anything else saved on the computer.
I used C++ to do file reading and writing, and then Linux, Windows, also used QT to write interface file reading and writing, now let’s try Python.
Read the file
The specific process is as follows:
(I will change the picture style later, I use the picture is also for everyone to see more intuitive)
Step 1: Open the file
Start by creating a test file, such as test.txt on your desktop, and write anything in it. Open your compiler, create a new project, and start programming.
file1 = open(r'D:\Users\asus\Desktop\test.txt'.'r',encoding='utf-8')
Copy the code
The variable file1 is used to store the read file data for further operations on the file.
(You can see that there are three parameters)
open(path,mode,encoding)
Copy the code
The first parameter is the address where the file is saved. It must be written clearly or the computer cannot find it
There are two methods, one is the absolute path to write the file, and one is the relative path to the file. If you want to use a relative path, you can also drag the file under your project file and then: look at the image
Right? All of these ways are ok, but if you are a beginner, you are advised to use the absolute path. What about absolute paths? Right click file -> Properties
Absolute path and relative path note points
- The absolute path is the most complete path, and the relative path is the path relative to the current folder, which is where the py file you wrote is placed!
- In Windows, \ is used to represent absolute paths and/is used to represent relative paths
- Don’t forget that \ is an escape character in Python, so there are always conflicts. To avoid pitfalls, Windows absolute paths are usually treated a little differently and written in one of two formats
open('D:\\Users\\asus\\Desktop\\test.txt')
# replace '\' with '\\'
open(r'D:\Users\asus\Desktop\test.txt')
# Prefix the path with the letter R
Copy the code
The second parameter is the permission bit, which is mainly like this:
R (read, read) | R read-only, pointer at the beginning, file does not exist error | Rb binary read only, the rest to the left | R + read and write, and the rest to the left | Rb + binary read and write, the rest same left |
---|---|---|---|---|
W (write, write) | If the file does not exist, it will be created. If the file does exist, it will be overwritten | Wb binary only write, the rest same left | W + read and write, and the rest to the left | Wb + binary read and write, other same left |
A (append, additional) | A appends, the file exists pointer is placed at the end, the file does not exist, new | Ab binary appended, the rest left | A + is appended and readable, and the rest is left | Ab + binary appended and readable, the rest same left |
Encoding = ‘UTF-8’; the encoding is utF-8 or GBK.
Step 2: Read the file
Once you open the file, you can use the read() function to read the file. But it’s not that simple. What if I want to read it line by line? What if I want to read one word at a time? How to do?
Here, we need to use a new function, readlines(), which reads line by line, as the name suggests.
Take a closer look:
That’s not a lot of information, so let’s do the next cut.
So we’ve separated out each row, but we’re going to separate out each number, right? Obviously we’re not satisfied yet.
So let’s use the string split function: split()
The join () function
Split () splits the string, and there is a join() function that merges the strings in the list.
a=['c'.'a'.'t']
b=' '
print(b.join(a))
c=The '-'
print(c.join(a))
Copy the code
Running results:
cat
c-a-t
Copy the code
One thing to notice here is that a join is a string.
One more note here: spilt is for strings.
Step 3: Close the file
To close the file, use the close() function.
file1.close()
Copy the code
Why close the file? There are two reasons for this: 1. There is a limit to the number of files a computer can open. If you open() too much without closing (), you can’t open any more files. 2. Ensure that the written content has been saved in the file.
Once the file is closed, it can no longer be read or written to. If you still need to read and write the file, open() again to open the file.
As a side note, we can use the keyword with to avoid opening a file and forgetting to close it, taking up resources, or when we are unsure of the appropriate time to close the file. The previous example could be written like this:
# use the with keyword
with open('test.txt'.'r') as file1:
#with open(' file address ',' read/write mode ')
# format: colons cannot be lost
file1.read()
Format: Indent operations on files
No need to close with close()
Copy the code
Written to the file
Open the file, I won’t say more, change ‘r’ to ‘W’, see the table above.
You u write, and when you’re done, you’ll be surprised to find that the original document has been washed out and rewritten. If you don’t want that to happen, you can change ‘w’ to ‘A’
So what’s b good for? The binary. Because a lot of files are stored in the computer, it is binary, not text that can be read by the naked eye. Like audio, like pictures, and so on. This is where you need to use the ‘B’ privilege.
Little practice
Learning this file read and write processing ah, let’s play a little game. Here’s a set of data:
The first column,42.25.65.14.78The second column,55.75.23.74.24The third column,58.45.31.15.65The fourth column,16.86.43.21.75
Copy the code
Then add the sum of each column to the bottom of the file:
Column 1,XX column 2,XXCopy the code
Put two images apart and put my implementation
My code
file= open(r'D:\Users\asus\Desktop\test.txt'.'r',encoding='GB2312')
#with open(r'D:\Users\asus\Desktop\test.txt','r',encoding='GBK') as file1:
file_lines = file.readlines()
file.close()
final_scores = []
for i in file_lines:
data = i.strip().split(', ')
sum = 0
for score in data[1] :sum = sum + int(score)
result = data[0] +str(sum) +'\n'
print(i)
final_scores.append(result)
The file has been closed
writer = open(r'D:\Users\asus\Desktop\test.txt'.'a',encoding='GBK')
writer.write('\n')
writer.writelines(final_scores)
writer.close()
Copy the code
One thing to note here is that your text file should not have ‘blank lines’, which are often invisible to the naked eye ,,,,,
I drew a circle to welcome you to this circle
I created a Python learning q & A group, interested friends can know: what is this group
Portal of the Straight group: Portal