将文件夹中的所有.dat文件传递给函数(Bitcoin、Python)

2024-09-27 21:24:35 发布

您现在位置:Python中文网/ 问答频道 /正文

我希望将指定文件夹中的(多个).dat区块链文件解析为python脚本。目的是打印出每个事务(这是临时的,计划是将人类可读的值写入数据库)。如果需要更多信息,我可以发送一个要点链接。在

def parseBlockFile(self, blockfile):
      print 'Parsing block file: %s\n' % blockfile
      with open(blockfile, 'rb') as bf:
         self.magic_no = read_uint4(bf)
         print 'magic_no:\t0x%8x' % self.magic_no

         self.blocksize = read_uint4(bf)
         print 'size:    \t%u bytes' % self.blocksize

         self.blockheader = BlockHeader()
         self.blockheader.parse(bf)
         print 'Block header:\t%s' % self.blockheader

         self.transaction_cnt = read_varint(bf)
         print 'Transactions: \t%d' % self.transaction_cnt

         self.transactions = []

         print 'List of transactions'
         for i in range(0, self.transaction_cnt):
            tx = Transaction()
            tx.parse(bf)
            self.transactions.append(tx)
            print '='*50
            print ' TX NUMBER: %d' % (i+1)
            print '='*50
            print tx
            print '\n'


def parseBlockFile(blockfile):
    block = Block()
    block.parseBlockFile(blockfile)

if __name__ == "__main__":
    import os  # Open a file
    path = "/Users/user_name/PycharmProjects/block_chain_parse/data/"
    dirs = os.listdir(path)
    # Find each file in the folder
    for file in dirs:
        print file #check the file makes it this far
        parseBlockFile(file) #pass each file

我得到的错误如下:

^{pr2}$

有什么想法吗?在


Tags: noselfreadparsemagicblockfiletransaction
3条回答

您是否正在运行与.dat文件相同的目录中的代码?调用parseBlockFile时尝试添加路径:

if __name__ == "__main__":
    import os  # Open a file
    path = "/Users/user_name/PycharmProjects/block_chain_parse/data/"
    dirs = os.listdir(path)
    # Find each file in the folder
    for file in dirs:
        print file #check the file makes it this far
        parseBlockFile(path+file) #pass each file

您可以使用^{},如下所示:

from glob import glob


if __name__ == "__main__":
    path = "H:/Workspaces_Python/test/"
    files = glob(path + "*.dat")

    for file in files:
        print(file)
        parseBlockFile(file) #pass each file

os.listdir(path)返回名称,而不是完整路径

parseBlockFile(file)更改为

fullpath = os.path.join(path,file)
if os.path.isfile(fullpath) and fullpath.endswith('.dat'):
  parseBlockFile(fullpath)

相关问题 更多 >

    热门问题