gpt4 book ai didi

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

转载 作者:太空宇宙 更新时间:2023-11-04 09:17:10 25 4
gpt4 key购买 nike

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 存在于同一目录中:

Removing duplicate rows from input files...
2 duplicate rows removed from A.csv!

期望的输出应该是:

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

最佳答案

您使用的检查条件不是在 python 中比较两个字符串的建议方法。除非你明确 interning字符串,你不应该使用 is 进行比较,因为不能保证它会返回 True使用 == 代替。

或者,您可以执行以下操作:

files=['A.csv', 'B.csv', 'C.csv']
filedict['A.csv']=(7,5)
filedict['B.csv']=(15,5)
filedict['C.csv']=(1,0)
print [(fname,filedict[fname]) for fname in files if filedict.has_key(fname) and os.path.isfile(fname)]

关于Python:检查列表中的文件是否存在,只有存在时才执行函数,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/7782691/

25 4 0
Copyright 2021 - 2024 cfsdn All Rights Reserved 蜀ICP备2022000587号
广告合作:1813099741@qq.com 6ren.com