我想用一个目录中的几个文本文件的名称填充dbf表的2个字段。
例如:
My_Dog_Named_Spot_02.txt
DBF读到:
Field1: My_Dog_Named_Spot
Field2: 02
有没有办法使用Python代码执行此操作?
答案 0 :(得分:0)
是。您可以使用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
答案 1 :(得分:-1)
类似的东西:
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()