You have to secretly learn Python, and then stun everyone (third day)

Article Directory

  • foreword
  • "Your Ruyi Golden Cudgel" has arrived, please sign for it
  • file read and write
  • computer code list
  • read file
  • Step 1: Open the file
  • Notes on absolute path and relative path
  • Step 2: Read the file
  • Step Three: Close the File
  • write to file
  • little practice
  • my code

foreword

This series of articles defaults that everyone has a certain C or C++ foundation, because I started Python after learning a little bit of C++. I would also like to thank everyone for your support. The first two articles are "condescending" in terms of visits, favorites, likes, and comments. Thank you, and some friends can't wait for the third article. I am really touched. Although I write slowly, playing two games less at night can also improve the update speed.

本系列文默认各位会百度,本系列也会着重培养各位的自主动手能力,毕竟我不可能把所有知识点都给你讲到,所以自己解决需求的能力就尤为重要,所以我在文中埋得坑请不要把它们看成坑,那是我留给你们的锻炼机会,请各显神通,自行解决。
123

img

Welcome to the Python community

If you have any difficulties in learning python and don’t understand, you can scan the CSDN official certification QR code below on WeChat to join python exchange learning, exchange questions, and help each other. There are good learning tutorials and development tools here.
insert image description here

"Your Ruyi Golden Cudgel" has arrived, please sign for it

Today we are going to talk about a more important part of Python, which is a very important reason why Python can suddenly rise. Have you ever thought that in this era of flying programming languages, there are veteran players C/C++, front-end PHP, H5, rookie Java, and MATLAB and R in the mathematics world. Why can Python stand out?

Yes, because Python is a panacea-like existence! It can call various packages to work for it. There are various functions in the packages. For example, if I want to use Python to process a lot of Excel tables, should I write the table processing functions myself? No, it is too troublesome to write by yourself, why not stand on the shoulders of giants? There is a package called 'csv', which is specially used to do this, so I can call it here.

Yes, it is the module call. After learning, you can use Python to batch process tables, do simple face recognition, and do some small projects. How about it, aren't you very excited! ! !

Well, take your time and take your time. Here, you need to have a competent compiler, which can be VS (supports py programming), pycharm, or others. I use pycharm, and VS is too big to open. Before downloading pycharm, you must first download a Python, now Beijing time: 2020-10-23, the latest version is 3.9.0. These two things have the latest versions recommended on their respective official websites, and the installation is also very convenient, basically all the way to next, but it is recommended not to install them on the C drive.

Everyone move! ! !

img

file read and write

After the functions and classes are finished, it is naturally the file read and write stream. During the period of time after learning the database, I once thought that reading and writing files was useless. Who still uses files these days, but later I found out that I was wrong.

computer code list

Let's first look at a computer code table:

Applicability characteristics of the code table ASCII code English uppercase and lowercase characters, does not support Chinese American inventions, occupies a small space GB2312 code, GBK code supports Chinese GBK code is an upgrade of GB2312 Unicode code supports international languages, occupies a large space, and has strong applicability. UTF-8 code supports international language conversion and occupies a small space. ASCII code is contained by UTF-8 code

File reading and writing is the main function of Python code calling computer files. It can be used to read and write text records, audio clips, Excel documents, save emails, and anything saved on the computer.

I have used C++ to read and write files, and on Linux and Windows, I have also used QT to write files with interfaces to read and write. Now let's try Python.

read file

The specific process is as follows:

img
(I will change the style of the picture in the future, I use the picture to make it more intuitive for everyone to see)

Step 1: Open the file

First, create a test file, such as the test.txt file on the desktop, write something 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')
1

The variable file1 is used to store the read file data, so as to perform the next operation on the file.

(It can be seen that there are three parameters)

open(path,mode,encoding)
1

Parameter interpretation: The first parameter is the storage address of the file, which must be written clearly, otherwise the computer cannot find it

There are two methods here, one is to write the absolute path of the file, and the other is the relative path of the file. The way I wrote above is an absolute path. If you want to use a relative path, you can also drag the file to your project file, and then: look at the picture

img

Right, these methods are all possible, but if you are a novice, it is recommended to use the absolute path, and the absolute path will be used after familiarity. How to see the absolute path? Right click on the file -> Properties

Notes on absolute path and relative path

  1. The absolute path is the most complete path, and the relative path refers to the path [relative to the current folder], which is the path of the folder where the py file you wrote is placed!
  2. In the Windows system, \ is often used to indicate an absolute path, and / is used to indicate a relative path.
  3. Don't forget that \ is an escape character in Python, so there are always conflicts. In order to avoid pitfalls, the absolute path of Windows usually needs to be processed a little bit and written in the following two formats
open('D:\\Users\\asus\\Desktop\\test.txt')
#将'\'替换成'\\'

open(r'D:\Users\asus\Desktop\test.txt')
#在路径前加上字母r
12345

The second parameter is the permission bit, mainly as follows:

r (read, read) r read-only, the pointer is at the beginning, if the file does not exist, an error will be reported rb binary read-only, the rest is the same as left r+ read and write, the rest is the same as left rb+ binary read and write, the rest is the same as left w (write, write) w write only, the file does not exist, create a new one, if it exists, overwrite wb binary write-only, the rest is the same as left w+ read and write, the rest is the same as left wb+ binary read and write, the rest is appended with left a (append, append) a, the file existence pointer is placed at the end, if the file does not exist, create ab binary append, the rest Same as the left a+append and readable, the rest are the same as the left ab+binary append and readable, the rest are the same as the left

The third parameter encoding='utf-8' indicates the encoding used for the returned data, generally utf-8 or gbk.

Step 2: Read the file

After opening the file, you can use the read() function to read. This has already been reflected in the above, the read() function. However, it's not that simple. What if I want to read it line by line? What if I want to read word by word? what to do?

img

Here, we need to use a new function readlines(), as the name suggests, read line by line.

Look carefully:

img

The amount of information is not large. After reading it, let's proceed to the next step.

Although each row is separated here, we want to separate each number, right? Obviously we are not satisfied yet. Then use the string cutting function: split()

img
split() splits the string, and there is also a join() function that merges the strings.

a=['c','a','t']
b=''
print(b.join(a))
c='-'
print(c.join(a))
12345

operation result:

cat
c-a-t
12

Step Three: Close the File

To close the file, use the close() function.

file1.close()   
1

Why do you want to close the file? There are two reasons: 1. The number of files that the computer can open is limited. If there are too many open()s without close(), the files cannot be opened any more. 2. It can ensure that the written content has been saved in the file.

After the file is closed, it can no longer be read or written to this file. If you still need to read and write this file, you need to open() again to open this file.

Here is another usage by the way. In order to avoid forgetting to close the file after opening it, occupying resources, or when we cannot determine the right time to close the file, we can use the keyword with. The previous example can be written as follows:

# 使用with关键字的写法
with open('test.txt','r') as file1:
#with open('文件地址','读写模式') as 变量名:
    #格式:冒号不能丢
    file1.read() 
    #格式:对文件的操作要缩进
    #格式:无需用close()关闭
1234567

write to file

Open the file, I won't say much, just change 'r' to 'w', see the table above for details.

img

You go to write, and after you finish writing, you will be pleasantly surprised to find that the content of the original document has been washed out and rewritten. . If you don't want this to happen, you can change 'w' to 'a'

So what's the use of b, the binary one. Because there are many files stored in the computer, it is binary, not text information that can be understood by the naked eye. Such as audio, such as pictures and so on. At this time, you need to use the blessing of 'b' permission.

little practice

After learning this file reading and writing processing, let's play a little game. Here is a set of data:

第一列,42,25,65,14,78
第二列,55,75,23,74,24
第三列,58,45,31,15,65
第四列,16,86,43,21,75
1234

Then sum each column of data and write it below the file:

第一列,XX
第二列,XX
···
123

Put a picture to separate, and then put my realization

img

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)

#这里表示文件已经被关闭了
writer = open(r'D:\Users\asus\Desktop\test.txt','a',encoding='GBK')
writer.write('\n')
writer.writelines(final_scores)
writer.close()
123456789101112131415161718192021

One thing to note here is that your text file cannot have 'blank lines', which are often invisible to the naked eye.

Guess you like

Origin blog.csdn.net/libaiup/article/details/131803099