Since some time ago I am trying to make a bash simulator using python, I am creating the tail and head commands, for this create 2 functions:
def head(textfile):
content = []
try:
file = open(textfile, "r")
for line in file:
content.append(line)
except:
print("[*] Error: No se ha podido abrir el archivo '{}'".format(textfile))
else:
for string in content[:5]:
print(string)
def tail(textfile):
content = []
try:
file = open(textfile, "r")
for line in file:
content.append(line)
except:
print("[*] Error: No se ha podido abrir el archivo '{}'".format(textfile))
else:
for string in content[len(content) - 5:]:
print(string)
The 2 functions are exaggeratedly similar, in fact they only change in one value:
for string in content[len(content) - 5:]:
# aquí el ':' está a la derecha
and
for string in content[:5]:
# y aquí el ':' está a la izquierda
I thought about changing that value to a parameter, but the ':' is set in different places (if I can not explain well read the comments in the code above) it bothers me to repeat code so: what is it that Can I do to have a single function?