我正在用Python编写一个脚本来自动化GIS流程。一般过程如下:
.dbf
.dbf
转换为.txt
文件.txt
文件.txt
文件。在大多数情况下,这个过程非常有效。我遇到的问题是.txt
文件不完整。 ArcGIS模型生成的.dbf
有7304条记录,但.txt
文件只有7232条记录。这几乎就像编写.txt
文件一样,脚本在到达结束之前就放弃了。我似乎无法弄清楚导致这种情况发生的原因。
我将附加脚本的一部分以及.txt
文件输出。任何帮助/建议将非常感谢。
DBF = r'Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ReportOutput\ERU.dbf'
output_directory = r'Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ERU_Output'
ERU_file = os.path.join(output_directory,'ERU.txt')
arcpy.AddMessage('Creating ERU file')
print "3"
report = open(ERU_file, "w")
cursor = arcpy.SearchCursor(DBF)
for row in cursor:
ACCT = row.getValue('ACCT')
STR_ACCT = str(ACCT)
NEW_ACCT = STR_ACCT.replace('.0','')
IMPAREA = row.getValue('IMPAREA')
STR_IMPAREA = str(IMPAREA)
NEW_IMPAREA = STR_IMPAREA.replace(".0",".00")
SWCODE = row.getValue('SWCODE')
STR_SWCODE = str(SWCODE)
report.write(NEW_ACCT + "," + NEW_IMPAREA + "," + STR_SWCODE + '\n')
del (ERU_file)
print "4"
arcpy.AddMessage('Adding headers')
headers = ['"ACCT","IMPAREA","SWCODE"']
filename = r"Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ERU_Output\ERU.txt"
tmp = open('TMP', 'w')
orig = open(filename, 'r')
tmp.write('\t'.join(headers) + '\n')
for line in orig.readlines():
tmp.write(line)
orig.close()
tmp.close()
arcpy.AddMessage('Headers added, renaming file')
os.remove(r'Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ERU_Final\ERU.txt')
os.rename('TMP', r'Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ERU_Final\ERU.txt')
print "5"
os.startfile(r'Q:\GIS_Mapping\BillingDept\ERU\DO_NOT_TOUCH\ERU_Final\ERU.txt')
arcpy.AddMessage('Done')
以下是没有标题的.txt
输出的一部分。如您所见,该过程运行正常,然后在222415613,0.00
之后停止。
600414006,0.00,1
602311015,0.00,1
910010858,0.00,1
2000716007,0.00,1
220735804,0.00,1
910010076,0.00,1
300724505,0.00,1
910012468,0.00,1
303737006,0.00,1
503143201,10079.33,2
213001881,0.00,1
2007212003,0.00,1
4080010042,0.00,1
4030010111,0.00,1
4090020013,0.00,1
910011618,0.00,1
221624400,0.00,1
600934006,0.00,1
505531404,0.00,1
215232207,0.00,1
600432514,0.00,1
600432011,0.00,0
404834003,0.00,1
222415613,0.00
附件是.dbf
的屏幕截图。正如您在222415613
记录之后所看到的那样,信息将继续正常,大约有50个左右的记录。
答案 0 :(得分:1)
将del (ERU_file)
更改为report.close()
。 del (ERU_file)
只删除标识文件位置的字符串,它实际上并不关闭打开的文件句柄并将数据刷新到磁盘。
或者更好的是,使用with
statement:
更改
report = open(ERU_file, 'w')
到
with open(ERU_file, 'w') as report:
并为您的cursor
声明和for
循环添加一定级别的缩进。
发生的事情是您使用orig = open(filename, 'r')
打开文件的第二个副本,而第一个副本report
仍处于打开状态,数据仍在写入缓冲区而不刷新到磁盘。当脚本完成运行时,该数据将作为python清理的一部分刷新到磁盘,这就是为什么当你自己看时它会在文件中看到它。