将文件夹中的所有.dat文件传递给函数(比特币,Python)

时间:2015-12-16 13:18:02

标签: python bitcoin

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

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

我得到的错误如下:

blk00000.dat
Parsing block file: blk00000.dat

Traceback (most recent call last):
  File "block.py", line 212, in <module>
    parseBlockFile(file) #pass each file
  File "block.py", line 203, in parseBlockFile
    block.parseBlockFile(blockfile)
  File "block.py", line 173, in parseBlockFile
    with open(blockfile, 'rb') as bf:
IOError: [Errno 2] No such file or directory: 'blk00000.dat'

有什么想法?

3 个答案:

答案 0 :(得分:1)

您可以使用glob,如下所示:

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

答案 1 :(得分:0)

您是否在与.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

答案 2 :(得分:0)

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

parseBlockFile(file)更改为

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