Snažím se to brát dvě prohlášení, a dát je do stejné funkce. To je součástí dlouhé dotaz importovat seznam z csv souborů (všech různých délkách, záhlaví, zápatí a sloupcích) do jednoho listu aplikace Excel pro import do databáze. Chtěl bych nastavit funkce, které lze volat k zefektivnění procesu.
Teď, když jsem spustit následující kód, funguje to a můžu použít dva parametry: beginFile a endFile určit začátek a konec dat pro import.
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)
Nicméně, když jsem umístit do funkce, pak jsem přijímat dva různé chybové zprávy, v závislosti na tom, jak jsem se napsat funkci. Pro tento první funkce, chybová zpráva je 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)
Pro tuto funkci, kód chyby je: 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)
Je to zjednodušující verze data, která používám pro testování: