如何在 python 中的一个函数中使用两个枚举语句?

How to use two enumerate statements in one function in python?

我正在尝试将两个语句放入同一个函数中。这是一个长查询的一部分,用于将 csv 文件列表(所有不同的长度、页眉、页脚和列)导入一个 Excel sheet 以导入数据库。我想设置可以调用的函数来简化流程。

现在,如果我 运行 下面的代码,它可以工作,我可以使用两个参数:beginFile 和 endFile 来确定导入数据的开始和结束。

beginning = 'eventID'
ending = 'The Line Listing is wrong'

beginFile = 0
endFile = 0

with open("testbooklet.csv") as myFile:
    for num, line in enumerate(myFile, 1):
        if beginning in line:
            beginFile = num
            
with open("testbooklet.csv") as myFile:
    for num, line in enumerate(myFile, 1):
        if ending in line:
            endFile = num
            
print(beginFile,endFile)

但是;如果我将其放入函数中,则会收到两条不同的错误消息,具体取决于我编写函数的方式。对于第一个函数,错误消息是 AttributeError: 'function' object has no attribute 'endFile'.

beginning = 'eventID'
ending = 'The Line Listing is wrong'

beginFile = 0
endFile = 0

# Define Function to find the first and last file lines
def fileinfo(file_name):
    global beginFile
    global endFile
    
    for num, line in enumerate(file_name, 1):
        if beginning in line:
            fileinfo.beginFile = num

# def endfileinfo(file_name):        
    for num, line in enumerate(file_name, 1):
        if ending in line:
            fileinfo.endFile = num

MyFile = open("testbooklet.csv")             
fileinfo(MyFile)
print(fileinfo.beginFile, fileinfo.endFile)

对于这个函数,错误代码是:NameError: name 'endFile' is not defined

beginning = 'eventID'
ending = 'The Line Listing is wrong'

beginFile = 0
endFile = 0

def fileinfo(file_name):
    global beginFile
    
    for num, line in enumerate(file_name, 1):
        if beginning in line:
            beginFile = num
   
    global endFile
            
    for num, line in enumerate(file_name, 1):
        if ending in line:
            endFile = num

            
MyFile = open("testbooklet.csv")
fileinfo(MyFile)
print(beginFile)
print(endFile)

这是我用于测试的数据的简化版本:

不要使用被函数改变的全局变量。取而代之的是让函数 return 随心所欲,并一次获得这两个信息:

def fileinfo(file):
    beginFile = None
    endFile = None
    for num, line in enumerate(file, 1):
        if beginning in line:
            beginFile = num
        if ending in line:
            endFile = num
            break  # No need to continue
    return beginFile, endFile  # return this information to caller


myFile = open("testbooklet.csv")             
beginFile, endFile = fileinfo(myFile)
print(beginFile, endFile)

不要使用两个循环。第一个是读取所有文件,因此第二个循环没有任何内容可读取。您可以在开头使用 file.seek(0) 到 return 来解决此问题,但在这种情况下没有必要 - 只需在一个循环中测试这两个条件即可。

您还应该使用参数和 return 值而不是全局变量。

def fileinfo(file, beginning, ending):
    beginFile = 0
    endFile = 0

    for num, line in enumerate(file, 1):
        if beginning in line:
            beginFile = num
        if ending in line:
            endFile = num

    return beginFile, endFile

with open("testbooklet.csv") as MyFile:
    begin, end = fileinfo(MyFile)