shelve
shelve is a simple data storage solution. It has only one function, which is open(). This function receives a parameter, which is the file name, and then returns a shelf object. You can use it to store things, and you can simply It is treated as a dictionary. When you finish storing it, call the close function to close it. This has a potential small problem, as follows:
[python] view plaincopy
>>> import shelve
>> > s = shelve.open('test.dat')
>>> s['x'] = ['a', 'b', 'c']
>>> s[ 'x'].append('d')
>>> s['x']
['a', 'b', 'c']
Where did the stored d go? In fact, it is very simple. d does not write back. You save ['a', 'b', 'c'] to x. When you read s['x'] again, s['x'] is just a Copy, and you did not write the copy back, so when you read s['x'] again, it read a copy from the source, so your newly modified content will not appear in the copy. , the solution is, the first one is to use a cached variable, as shown below
[python] view plaincopy
>>> temp = s['x']
>>> temp.append ('d')
>>> s['x'] = temp
>>> s['x']
['a', 'b', 'c', 'd' ]
There is another method in python2.4, which is to assign the value of the writeback parameter of the open method to True. In this case, all the content after you open will be in the cache. When you close, it will be all at once. written to the hard drive. This is recommended if the amount of data is not very large.
The following is the code for a simple database based on shelve
[python] view plaincopy
#database.py
import sys, shelve
def store_person(db):
"""
Query user for data and store it in the shelf object
""" pid = raw_input('Enter unique ID number: ')
person = {}
person['name'] = raw_input('Enter name: ')
person['age'] = raw_input( 'Enter age: ')
person['phone'] = raw_input('Enter phone number: ') db[pid] = person
def lookup_person(db):
"""
Query user for ID and desired field , and fetch the corresponding data from
the shelf object
"""
pid = raw_input('Enter ID number: ')
field = raw_input('What would you like to know? (name, age, phone) ')
field = field.strip().lower()
print field.capitalize() + ':',
db[pid][field]
def print_help():
print 'The available commons are: '
print ' store :Stores information about a person'
print 'lookup :Looks up a person from ID number'
print 'quit :Save changes and exit'
print '? rint this message'
def enter_command(): cmd = raw_input ('Enter command (? for help): ')
cmd = cmd.strip().lower()
return cmd
def main():
database = shelve.open('database.dat') try:
cmd elif cmd == 'lookup':
lookup_person(database)
elif cmd == '?':
print_help()
elif cmd == 'quit':
return
finally:
database.close()
if __name__ == '__main__': main()

Create multi-dimensional arrays with NumPy can be achieved through the following steps: 1) Use the numpy.array() function to create an array, such as np.array([[1,2,3],[4,5,6]]) to create a 2D array; 2) Use np.zeros(), np.ones(), np.random.random() and other functions to create an array filled with specific values; 3) Understand the shape and size properties of the array to ensure that the length of the sub-array is consistent and avoid errors; 4) Use the np.reshape() function to change the shape of the array; 5) Pay attention to memory usage to ensure that the code is clear and efficient.

BroadcastinginNumPyisamethodtoperformoperationsonarraysofdifferentshapesbyautomaticallyaligningthem.Itsimplifiescode,enhancesreadability,andboostsperformance.Here'showitworks:1)Smallerarraysarepaddedwithonestomatchdimensions.2)Compatibledimensionsare

ForPythondatastorage,chooselistsforflexibilitywithmixeddatatypes,array.arrayformemory-efficienthomogeneousnumericaldata,andNumPyarraysforadvancednumericalcomputing.Listsareversatilebutlessefficientforlargenumericaldatasets;array.arrayoffersamiddlegro

Pythonlistsarebetterthanarraysformanagingdiversedatatypes.1)Listscanholdelementsofdifferenttypes,2)theyaredynamic,allowingeasyadditionsandremovals,3)theyofferintuitiveoperationslikeslicing,but4)theyarelessmemory-efficientandslowerforlargedatasets.

ToaccesselementsinaPythonarray,useindexing:my_array[2]accessesthethirdelement,returning3.Pythonuseszero-basedindexing.1)Usepositiveandnegativeindexing:my_list[0]forthefirstelement,my_list[-1]forthelast.2)Useslicingforarange:my_list[1:5]extractselemen

Article discusses impossibility of tuple comprehension in Python due to syntax ambiguity. Alternatives like using tuple() with generator expressions are suggested for creating tuples efficiently.(159 characters)

The article explains modules and packages in Python, their differences, and usage. Modules are single files, while packages are directories with an __init__.py file, organizing related modules hierarchically.

Article discusses docstrings in Python, their usage, and benefits. Main issue: importance of docstrings for code documentation and accessibility.


Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

VSCode Windows 64-bit Download
A free and powerful IDE editor launched by Microsoft

SublimeText3 English version
Recommended: Win version, supports code prompts!

DVWA
Damn Vulnerable Web App (DVWA) is a PHP/MySQL web application that is very vulnerable. Its main goals are to be an aid for security professionals to test their skills and tools in a legal environment, to help web developers better understand the process of securing web applications, and to help teachers/students teach/learn in a classroom environment Web application security. The goal of DVWA is to practice some of the most common web vulnerabilities through a simple and straightforward interface, with varying degrees of difficulty. Please note that this software

SublimeText3 Chinese version
Chinese version, very easy to use

SecLists
SecLists is the ultimate security tester's companion. It is a collection of various types of lists that are frequently used during security assessments, all in one place. SecLists helps make security testing more efficient and productive by conveniently providing all the lists a security tester might need. List types include usernames, passwords, URLs, fuzzing payloads, sensitive data patterns, web shells, and more. The tester can simply pull this repository onto a new test machine and he will have access to every type of list he needs.
