python执行列表中的函数_Python:检查列表中的文件是否存在,只有存在时才执行函数...

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

  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值