Small knowledge, big challenge! This article is participating in the creation activity of “Essential Tips for Programmers”.

This article also participated in the “Digitalstar Project” to win a creative gift package and creative incentive money

file

  • A collection of data information that holds information for a long time
  • Common operations
    • Open and close (once the file is open, it needs to be closed)
    • Read and write the content
    • To find the

The open function

  • The open function is responsible for opening files and takes many parameters
  • First argument: must have, file path and name
  • Mode: indicates how the file is opened
    • R: Open it in read-only mode
    • W: Open the write mode, it will overwrite the previous content
    • X: Open the creation mode. If the file already exists, an error message is displayed
    • A: Write files in append mode
    • B: Write in binary mode
    • T: Open in text mode
    • +; Read/write
Open the file and write it
# r indicates that the following string content does not need to be escaped
# f is called the file handle
f = open(r"test01.txt".'w')
The file must be closed after it is opened
f.close()

Open a file in write mode. The default is create a file if there is no file
Copy the code

With statement

  • Using technology with statement is a technique called context management protocol (ContextManagementProtocol)
  • Automatically determine the scope of a file and automatically close open file handles that are no longer in use
# with statement example

with open(r"test01.txt".'r') as f:
    pass
    # the following block starts the operation on file f
    # There is no need to use close to close file f in this module
Copy the code
# with case

with open(r"test01.txt".'r') as f:
    Read content by line
    strline = f.readline()
    # This structure guarantees that the file can be read in its entirety until the end
    while strline:
        print(strline)
        strline = f.readline()
Copy the code
If I should meet again, how should I greet you? With tears, with silence.Copy the code
# list takes the open file as an argument, and takes each line of the file as an element

with open(r"test01.txt".'r') as f:
    # create list with open file f as argument
    l = list(f)
    for line in l:
        print(line)
Copy the code
If I should meet again, how should I greet you? With tears, with silence.Copy the code
# read reads the contents of a file by character
# Allows the input argument to determine how many characters to read, if not specified, from the current position to the end
# Otherwise, read a specified number of characters from the current position

with open(r"test01.txt".'r') as f:
    strChar = f.read(1)
    print(len(strChar))
    print(strChar)
Copy the code
1 the falseCopy the code

seek (offset, from)

  • Move the read position of a file, also called the read pointer
  • Value range of from:
    • 0: offset from the file header
    • 1: offset from the current file location
    • 2: offset from the end of the file
  • The units of movement are bytes
  • A Chinese character consists of several bytes
  • Return file for current location only
# the seek case
After opening the file, read from byte 5

The read/write pointer is at 0, the beginning of the file
with open(r"test01.txt".'r') as f:
    # seek moves in bytes
    f.seek(4.0)
    strChar = f.read()
    print(strChar)
Copy the code
When I meet you, how shall I greet you? With tears, with silence.Copy the code
# Exercise about reading files
Open the file, read the contents in groups of three characters, and display them on the screen
Take a one-second break each time you read it

# pause the program by using the sleep function under time

import time

with open(r"test01.txt".'r') as f:
    The units of the # read parameter are characters, which can be interpreted as a Chinese character
    strChar = f.read(3)
    while strChar:
        print(strChar)
        The sleep parameter is in seconds
        time.sleep(1)
        strChar = f.read(3)
Copy the code
If he should meet, how should I greet you? With tears, with silence.Copy the code
The tell function is used to display the current position of the file read pointer

with open(r"test01.txt".'r') as f:
    strChar = f.read(3)
    pos = f.tell()
    
    while strChar:
        print(pos)
        print(strChar)
        
        strChar = f.read(3)
        pos = f.tell()
        
# Here are the results:
The return number of # tell is in bytes
# read is in bytes
Copy the code
If he meets you on the 12th, how can I greet you on the 24th? 36 eyes 42 tears, 48 silence 50.Copy the code

File write operation – write

  • Write (STR) : Writes a string to a file
  • Writeline (STR) : Writes a string line to a file
  • The difference between:
    • Write function arguments must be strings
    • The writeline function argument can be either a string or a sequence of strings
# write case
# 1. Append a line of poetry to the file

# a means append
with open(r"test01.txt".'a') as f:
    # Notice that the string contains a newline character
    f.write("Life is not just a temporary existence, \n there is a distant existence.")
Copy the code
# You can write rows directly with Writelines
# writelines specifies how many lines are written. The parameters can be a list
with open(r"test01.txt".'a') as f:
    # Notice that the string contains a newline character
    f.writelines("There's more to life than just the present.")
    f.writelines("And faraway goji berries.")
Copy the code
help(f.writelines)
Copy the code
Help on built-in function writelines:

writelines(lines, /) method of _io.TextIOWrapper instance
Copy the code
l = ["I"."love"."you"]
with open(r"test01.txt".'w') as f:
    # Notice that the string contains a newline character
    f.writelines(l)
Copy the code

Persistence – pickle

  • Serialization (persistence, landing) : Saves information about a program’s execution to disk
  • Deserialization: The reverse of serialization
  • Pickle: A serialization module provided by Python
  • Pickle. dump: serialize
  • Pickle. load: deserialize
# serialize cases
import pickle

age = 19

with open(r"test01.txt".'wb') as f:
    pickle.dump(age, f)
Copy the code
Deserialize the case

import pickle

with open(r"test01.txt".'rb') as f:
    age = pickle.load(f)
    print(age)
Copy the code
19
Copy the code
# serialize cases
import pickle

a = [19.'ruochen'.'i love you'[175.51]]

with open(r"test01.txt".'wb') as f:
    pickle.dump(a, f)
Copy the code
with open(r"test01.txt".'rb') as f:
    a = pickle.load(f)
    print(a)
Copy the code
[19, 'ruochen', 'i love you', [175, 51]]
Copy the code

Persistence – shelve

  • Persistence tool
  • Similar to the dictionary, using KV pair to save data, access is similar to the dictionary
  • The open and close
Create a file using shelve and use it
import shelve

# Open file
SHV is equivalent to a dictionary
shv = shelve.open(r"shv.db")

shv['one'] = 1
shv['two'] = 2
shv['three'] = 3

shv.close()

# From the above examples, shelve automatically creates not only a shv.db file, but also other file formats
Copy the code
# shelve read the case

shv = shelve.open(r'shv.db')

try:
    print(shv['one'])
    print(shv['threee'])
except Exception as e:
        print("1")
finally:
    shv.close()
Copy the code
1
1
Copy the code

Shelve features

  • Multiple applications cannot write data concurrently
    • To solve this problem, flag=r can be used when open
  • Write back to the problem
    • Shelve does not wait for persistent objects to make any changes by default
    • Solution: force writeback: writeback=True
# shelve read-only open
import shelve

shv = shelve.open(r'shv.db', flag='r')

try:
    k1 = shv['one']
    print(k1)
finally:
    shv.close()
Copy the code
1
Copy the code
import shelve


shv = shelve.open(r'shv.db')
try:
    shv['one'] = {"eins":1."zwei":2."drei":3}
finally:
    shv.close()
    
shv = shelve.open(r'shv,db')
try:
    one = shv['one']
    print(one)
finally:
    shv.close()
Copy the code
---------------------------------------------------------------------------

KeyError                                  Traceback (most recent call last)

D:\Anaconda3\lib\shelve.py in __getitem__(self, key)
    110         try:
--> 111             value = self.cache[key]
    112         except KeyError:


KeyError: 'one'


During handling of the above exception, another exception occurred:


KeyError                                  Traceback (most recent call last)

<ipython-input-73-b418c9ea023b> in <module>
     10 shv = shelve.open(r'shv,db')
     11 try:
---> 12     one = shv['one']
     13     print(one)
     14 finally:


D:\Anaconda3\lib\shelve.py in __getitem__(self, key)
    111             value = self.cache[key]
    112         except KeyError:
--> 113             f = BytesIO(self.dict[key.encode(self.keyencoding)])
    114             value = Unpickler(f).load()
    115             if self.writeback:


D:\Anaconda3\lib\dbm\dumb.py in __getitem__(self, key)
    151             key = key.encode('utf-8')
    152         self._verify_open()
--> 153         pos, siz = self._index[key]     # may raise KeyError
    154         with _io.open(self._datfile, 'rb') as f:
    155             f.seek(pos)


KeyError: b'one'
Copy the code
# shelve forgot to write back. Mandatory write back is required
shv = shelve.open(r"shv.db")
try:
    k1 = shv['one']
    print(k1)
    Once shelve is closed, the content remains in memory and is not written back to the database
    k1["eins"] = 100
finally:
    shv.close()
    
shv = shelve.open(r"shv.db")
try:
    k1 = shv['one']
    print(k1)
finally:
    shv.close()
Copy the code
{'eins': 1, 'zwei': 2, 'drei': 3}
{'eins': 1, 'zwei': 2, 'drei': 3}
Copy the code
# shelve forgot to write back. Mandatory write back is required
shv = shelve.open(r"shv.db", writeback=True)
try:
    k1 = shv['one']
    print(k1)
    Once shelve is closed, the content remains in memory and is not written back to the database
    k1["eins"] = 100
finally:
    shv.close()
    
shv = shelve.open(r"shv.db")
try:
    k1 = shv['one']
    print(k1)
finally:
    shv.close()
Copy the code
{'eins': 1, 'zwei': 2, 'drei': 3}
{'eins': 100, 'zwei': 2, 'drei': 3}
Copy the code
# shelve uses with to manage context

with shelve.open(r'shv.db', writeback=True) as shv:
    k1 = shv['one']
    print(k1)
    k1['eins'] = 1000
    
with shelve.open(r"shv.db") as shv:
    print(shv['one'])
Copy the code
{'eins': 100, 'zwei': 2, 'drei': 3}
{'eins': 1000, 'zwei': 2, 'drei': 3}
Copy the code

Finally, welcome to pay attention to my personal wechat public account “Little Ape Ruochen”, get more IT technology, dry goods knowledge, hot news