Для достижения того, что вы запрашиваете, функция в порядке, и важно вызывать ее с правильными аргументами и отличать их от значений по умолчанию.
В коде поведение по умолчанию -используйте ,
в качестве разделителя, чтобы не пропустить первую строку файла.Чтобы на самом деле разделить с помощью |
и пропустить первую строку (то есть заголовок), тогда мы установим seperator='|'
и header = True
, когда мы ее вызовем.
# Function is fine, leave as-is
#
def file_reader(path, num_fields, seperator = ',', header = False):
try:
fp = open(path, "r", encoding="utf-8")
except FileNotFoundError:
raise FileNotFoundError("Unable to open file.")
else:
with fp:
for n, line in enumerate(fp, 1):
fields = line.rstrip('/n').split(seperator)
if len(fields) != num_fields:
raise ValueError("Unable to read file.")
elif n == 1 and header:
continue
else:
yield tuple([f.strip() for f in fields])
# Example file afile.txt contains these lines:
# alfa|beta|gamma|delta
# 1|2|3|4
# a|b|c|d
# here we call the function:
filename = 'afile.txt'
for x in file_reader(filename, 4, '|', True): #note the separator and header
print(x)