Python Modify the column specified in the DBF file
- 2021-08-31 08:30:55
- OfStack
1. Requirements:
A company receives a batch of DBF files every day, and the dealstat field is set to 1 (processed) after A system processes them in real time. Now the B system also needs to process this file every night, so the dealstat field in the file needs to be modified to be empty (unprocessed).
2. Analysis:
1. A copy should be created for modification
Answer: Use shutil. copy
2. Modify DBF
Answer: Use the dbf module. The documents found in this module are old and need to be understood in combination with the code.
3. Code implementation:
#!/usr/bin/env python
# _*_ coding:utf-8 _*_
"""
@Time : 2020-01-15 10:43
@Author : Peanut_C
@FileName: DBF_Modifier.py
"""
import os
import time
import shutil
import dbf
source_dir = r'D:\'
destination_dir = r'E:\'
""" Delete old files in the destination folder """
os.chdir(destination_dir)
for file in os.listdir(destination_dir):
os.remove(file)
print('INFO ===>>> History file deletion complete! \n')
""" File copy task """
os.chdir(source_dir)
for file in os.listdir(source_dir):
shutil.copy(file, destination_dir)
print('INFO ===>>> Today's file copy is complete! \n')
"""DBF Modify task """
os.chdir(destination_dir)
for file in os.listdir(destination_dir):
tb = dbf.Table(file) # Create tb Instances
# print(tb) # Print tb Information
titles = dbf.get_fields(file) # Print the header as a list
# print(titles)
if 'dealstat' in titles:
flag = 0 # File modification mark
tb.open(mode=dbf.READ_WRITE) # Read-write mode turned on tb
for record in tb:
with record as r:
if r.dealstat is not None:
# print(r.dealstat)
r.dealstat = ''
flag = 1 # Modify to change the tag to 1
# print(r.dealstat)
else:
continue
# print(record.dealstat)
tb.close()
if flag == 0:
print(file + "===>>> There is no data to modify! \n")
else:
print(file + "===>>>DealStat The field has been modified! \n")
else:
print(file + "===>>> No DealStat Fields! \n")
print('INFO ===>>> Today's document has been revised! \n')
4. Operation:
Run the program, first empty the target directory, then create a copy of the file, and finally process the DBF files in the directory in turn.
It's a simple feature, but it saves a lot of time, and other modifications to DBF can be made by analogy.
I hope I can help friends in need.
Give me a lot of advice!
The above is Python modifies DBF file specified column details, more about Python modifies DBF file information please pay attention to this site other related articles!