繁体   English   中英

将文本文件NAMES添加到dbf中的字段

[英]Add text file NAMES to fields in a dbf

我想用目录中几个文本文件的名称填充dbf表的2个字段。

例如:

My_Dog_Named_Spot_02.txt 

DBF读取:

Field1: My_Dog_Named_Spot
Field2: 02

有没有办法使用Python代码来做到这一点?

是。 您可以使用os.glob('some/dir/with/files/*.txt')获得文本文件列表,并使用dbf创建/使用dbf并存储结果:

import dbf
import os

with dbf.Table('some_dbf') as files:
    for filename in os.glob('*.txt')
        base, number = os.path.splitext(os.path.basename(filename))[0].rsplit('_', 1)
        files.append((base, number)) # assuming field1 and field2 are the first two fields

像这样的东西:

import os

with open('out.dbf', 'w') as od:

    for root, subdirs, files in os.walk(some_directory):
        for fn in files:
            (base, ext) = os.path.splitext(fn)
            if ext == '.txt':
                toks = base.split('_')
                od.write('Field1: ' + '_'.join(toks[:-1]))
                od.write('Field2: ' + toks[-1])

od.close()

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM