File operation knowledge exercises

File operations:

    Reading, writing, adding and judging the file encoding form of the file

 

1. File read (read only):

      f = open('xx.txt', 'r', encoding = 'encoding form (such as utf-8)') # What form of code is used, read in what form, otherwise garbled code will occur

      data = f.read()

      print(data) # print the contents of the file

      f.close()

 

2. File writing (write only):

      f = open('xx.txt', 'w', encoding = 'encoding form (such as utf-8)')

      data = f.write() # Create (empty 'xx.txt') and write Note: Only str can be written

      print(data) # The output here is the return value of write() (that is, the length of the input characters)

      f.close() 

 

3. File reading (read in binary form):

      f = open('xx.txt', 'rb') # Because the binary form in the file is read, there is no encoding problem

      f.read()

      f.close()

 

4. File writing (write binary):

      f = open('xx.txt', 'wb')

      f.write('xx') ## The 'xx' here needs to be written in binary code i.e. 0010 1100 or "fuck you".encode("utf-8") form

      f.close

 

5. Addition of files (written on the original basis):

      f = open('xx.txt', 'a', encoding = 'encoding form (such as utf-8)')

      f.write('xx')

      f.close()

 

6. The read and write mode of the file (both read and write):

      f = open('xx.txt', 'r+', encoding = 'encoding form (such as utf-8)')

      f.read() # Because it is a read-write mode, it can only be read and then written

        f.write('xx')      

      f.close     

 

7. File write and read mode (both write and read):

      

                    f = open('xx.txt', 'r+', encoding = 'encoding form (such as utf-8)')

      f.read() # Because it is a write-read mode, it can only be written first and then read

        f.write('xx') ###Note: Because writing first and then reading, writing is to create and clear the content of the original 'xx.txt', so this is basically not used

      f.close     

 

8. Confirmation of file encoding form:

 

      import  chardet

      f = open('xx.txt','rb')

      data = f.read()

      f.close

      result = chardet.detect(data)

      print(result)

 

 

9. Exercise (coding and file handling):

    

i. Please specify the default encoding for python2 and python3

      pyhton2 default encoding is gbk

      python3 default encoding is utf-8

 

ii. Why Chinese garbled characters appear? Please list the reasons for the garbled characters

      

      Use a decoding method to open b code

      

  

Guess you like

Origin http://43.154.161.224:23101/article/api/json?id=325887963&siteId=291194637