📜  如何在Python中搜索泡菜文件?

📅  最后修改于: 2022-05-13 01:54:24.303000             🧑  作者: Mango

如何在Python中搜索泡菜文件?

先决条件:泡菜文件

Python pickle 模块用于序列化和反序列化Python对象结构。 Python中的任何对象都可以进行pickle,以便将其保存在磁盘上。 pickle 的作用是先“序列化”对象,然后再将其写入文件。 Pickling 是一种将Python对象(列表、字典等)转换为字符流的方法。这个想法是这个字符流包含在另一个Python脚本中重建对象所需的所有信息

Pickle 一次序列化一个对象,并读回一个对象——pickle 的数据按顺序记录在文件中。

如果您只是执行pickle.load,您应该读取序列化到文件中的第一个对象(而不是您编写的最后一个)。

在反序列化第一个对象后,文件指针位于下一个对象的开头——如果你再次调用 pickle.load,它将读取下一个对象——这样做直到文件结束。

使用的功能:

  • dump() – 用于将 obj 的pickle 表示写入打开的文件对象文件。

句法:

  • load() – 用于从打开的文件对象文件中读取腌制对象表示,并返回指定的重组对象层次结构。

句法:

  • seek(0)- Pickle 记录可以连接到一个文件中,所以是的,您可以多次 pickle.load(f),但文件本身并没有以可以让您搜索给定记录的方式编入索引。您的 f.seek(0) 正在做的是寻找文件中的第三个字节,该字节位于 pickle 记录的中间,因此是不可选择的。如果您需要随机访问,您可能需要查看内置的 shelve 模块,该模块使用数据库文件模块在 pickle 之上构建了一个类似字典的界面。
  • truncate() -改变文件大小

下面给出的是添加到pickle文件的植入。

程序:

Python3
import pickle
  
  
print("GFG")
  
def write_file():
  
    f = open("travel.txt", "wb")
    op = 'y'
  
    while op == 'y':
  
        Travelcode = int(input("enter the travel id"))
        Place = input("Enter the Place")
        Travellers = int(input("Enter the number of travellers"))
        buses = int(input("Enter the number of buses"))
  
        pickle.dump([Travelcode, Place, Travellers, buses], f)
        op = input("Dp you want to continue> (y or n)")
  
    f.close()
  
  
print("entering the details of passengers in the pickle file")
write_file()


Python3
import pickle
  
  
print("GFG")
  
def search_file():
    f = open("travel.txt", 'rb')
    t_code = int(input("Enter the travel code to traveller : "))
      
    while True:
        try:
            
            L = pickle.load(f)
              
            if L[0] == t_code:
                print("Place", L[1], "\t\t Travellers :",
                      L[2], "\t\t Buses :", L[3])
                  
                break
                  
        except EOFError:
            
            print("Completed reading details")
    f.close()
  
  
print("entering the details of passengers in the pickle file")
write_file()
  
print("Search the file using the passenger Code")
search_file()


创建pickle文件并加载数据成功后,就可以进行搜索了。

方法:

  • 导入模块
  • 打开泡菜文件
  • 取一些元素作为搜索的基础
  • 如果找到则显示结果

程序:

蟒蛇3

import pickle
  
  
print("GFG")
  
def search_file():
    f = open("travel.txt", 'rb')
    t_code = int(input("Enter the travel code to traveller : "))
      
    while True:
        try:
            
            L = pickle.load(f)
              
            if L[0] == t_code:
                print("Place", L[1], "\t\t Travellers :",
                      L[2], "\t\t Buses :", L[3])
                  
                break
                  
        except EOFError:
            
            print("Completed reading details")
    f.close()
  
  
print("entering the details of passengers in the pickle file")
write_file()
  
print("Search the file using the passenger Code")
search_file()

输出: