Python怪。。。请温柔一点。在我当前的程序中,我有一个3个文件的列表,这些文件可能位于我当前的目录中,也可能不在我的当前目录中。如果它们确实位于我的目录中,我希望能够为它们分配值,以便以后在其他函数中使用。如果文件不在目录中,则不应为其赋值,因为该文件无论如何都不存在。我目前掌握的代码如下:import os, csv
def chkifexists():
files = ['A.csv', 'B.csv', 'C.csv']
for fname in files:
if os.path.isfile(fname):
if fname == "A.csv":
hashcolumn = 7
filepathNum = 5
elif fname == "B.csv":
hashcolumn = 15
filepathNum = 5
elif fname == "C.csv":
hashcolumn = 1
filepathNum = 0
return fname, hashcolumn, filepathNum
def removedupes(infile, outfile, hashcolumn):
fname, hashcolumn, filepathNum = chkifexists()
r1 = file(infile, 'rb')
r2 = csv.reader(r1)
w1 = file(outfile, 'wb')
w2 = csv.writer(w1)
hashes = set()
for row in r2:
if row[hashcolumn] =="":
w2.writerow(row)
hashes.add(row[hashcolumn])
if row[hashcolumn] not in hashes:
w2.writerow(row)
hashes.add(row[hashcolumn])
w1.close()
r1.close()
def bakcount(origfile1, origfile2):
'''This function creates a .bak file of the original and does a row count to determine
the number of rows removed'''
os.rename(origfile1, origfile1+".bak")
count1 = len(open(origfile1+".bak").readlines())
#print count1
os.rename(origfile2, origfile1)
count2 = len(open(origfile1).readlines())
#print count2
print str(count1 - count2) + " duplicate rows removed from " + str(origfile1) +"!"
def CleanAndPrettify():
print "Removing duplicate rows from input files..."
fname, hashcolumn, filepathNum = chkifexists()
removedupes(fname, os.path.splitext(fname)[0] + "2.csv", hashcolumn)
bakcount (fname, os.path.splitext(fname)[0] + "2.csv")
CleanAndPrettify()
我遇到的问题是代码在列表中运行,并在找到的第一个有效文件处停止。在
我不确定我是否完全错误地思考了这件事,但我认为我做得对。在
此程序的当前输出(A.csv、B.csv和C.csv位于同一目录中):
^{pr2}$
所需输出应为:Removing duplicate rows from input files...
2 duplicate rows removed from A.csv!
5 duplicate rows removed from B.csv!
8 duplicate rows removed from C.csv!
…然后继续创建.bak文件的下一部分。
在同一目录下,此程序的输出不包含任何CSV文件:UnboundLocalError: local variable 'hashcolumn' referenced before assignment