def reverse_lines(n):
with open(n,'r') as fie:
data = fie.read().split('\n')
if len(data)== 0:
pass
else:
print(data[0])
ding = data[1::]
fie = '\n'.join(ding)
file(n).truncate()
file(n).write(fie)
return reverse_lines(n)
I am struggling to write to the file because I only have the file name. I do not understand the interaction between what I return and the parameter it accepts.
CodePudding user response:
This answer I consider poor because it abuses the parameters and also manually catches a StopIteration
. Still it is recursive and produces the correct output:
def reverse_lines(n, contents = None):
if not contents:
with open(n, 'r') as file:
contents = (line.strip() for line in file)
reverse_lines(n, contents)
else:
try:
line = next(contents)
reverse_lines(n, contents)
print(line)
except StopIteration:
pass
reverse_lines('poem.txt')
Output as requested.
CodePudding user response:
My approach would be to make a lines
generator that generates the lines of a given filename
-
def lines(filename):
with open(filename) as f:
for line in f:
yield line.strip()
And a generic reverse
generator that reverses any iterable, it
-
def reverse(it):
stop = {}
v = next(it, stop)
if v is stop: return
yield from reverse(it)
yield v
Combine them for the desired effect -
for line in reverse(lines("myfile.txt")):
print(line)
Given myfile.txt
-
a
b
c
d
e
f
g
Output -
g
f
e
d
c
b
a