我在当地市政当局工作并为警察部门提供地图。每个月,我都会收到他们用来绘制电话的报告。有一段时间,我手动编辑了CSV文件以导入我的程序。使用newboston视频和stackoverflow论坛,我能够弄清楚如何使用python自动化我的进程,但我为每个进程创建了单独的脚本。每个月,我现在运行4个单独的脚本,这需要花费与手动编辑一样多的时间,但我不必担心我的错误。因为我仍然是python的新手,所以我很难将这四个拼凑成一个脚本。我的过程是删除报告的前9行,因为这是我绘图所不需要的信息。然后我删除来电者姓名,来电者电话和来电者地址字段,因为这不应该是公共知识。我的映射程序不允许标题名称中包含特殊字符,因此我需要替换它们。最后,官员应该启动一个程序来获得他们在现场的位置,但不幸的是它通常不会发生所以我需要为那些插入0,0。到目前为止,我已经在每个进程之后创建了一个新文件,并对其进行硬编码以读取从第一个进程生成的文件以运行第二个进程。每次我尝试将所有脚本放在一起时,我都会遇到错误。如果有人能提供一点指导,我会非常感激。
#deleteRows
import sys, os
inputFileName = "C:\policeDept\report.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_Rows.csv"
try:
#OPEN the input and output files
infile = open (inputFileName, 'r')
outfile = open (outputFileName, 'w')
lines = infile.readlines()
infile.close()
outfile.write(''.join(lines[9:]))
outfile.close()
except IOError:
print inputFileName, "Does not exist."
#deleteColumns
import sys, os, csv
inputFileName = "C:\policeDept\report_Rows.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_Columns.csv"
fields = ["CallerName", "CallerPhone","CallerAddress"]
with open(inputFileName) as infile, open(outputFileName, "w") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, fields, extrasaction="ignore")
w.writeheader()
for row in r:
w.writerow(row)
import csv, os, sys
input = open('C:/policeDept/report_Rows_Columns.csv', 'r')
output = open('C:/policeDept/report_Rows_Columns_Characters.csv', 'w')
conversion = '-"/.$'
newtext = '_'
index = 0
for line in input:
if index == 0:
for c in conversion:
line = line.replace(c, newtext)
output.write(line + "\n")
index += 1
input.close()
output.close()
import sys, os, csv
inputFileName = "C:\policeDept\report_Rows_Columns_Characters.csv"
outputFileName = os.path.splitext(inputFileName)[0] + "_Coordinates.csv"
with open(inputFileName, "rb") as infile, open(outputFileName, "wb") as outfile:
r = csv.DictReader(infile)
w = csv.DictWriter(outfile, r.fieldnames)
w.writeheader()
for row in r:
if not row["Lat"].strip():
row["Lat"] = "0"
if not row["Long"].strip():
row["Long"] = "0"
w.writerow(row)