Python

Задача 2. Дзен Пайтона

Что нужно сделать

В файле zen.txt хранится так называемый Дзен Пайтона — текст философии программирования на языке Python. Выглядит он так:



Beautiful is better than ugly.

Explicit is better than implicit.

....
If the implementation is easy to explain, it may be a good idea.

Namespaces are one honking great idea -- let's do more of those!



Напишите программу, которая выводит на экран все строки этого файла в обратном порядке.



Кстати, попробуйте открыть консоль Python и ввести команду “import this”.



Результат работы программы:

Namespaces are one honking great idea -- let's do more of those!

If the implementation is easy to explain, it may be a good idea.


МОЙ КОД:

 zen_file = open('zen.txt', 'r') 
zen_l = []

for i_line in zen_file:
zen_l.append(i_line)
zen_l.reverse()
print(''.join(zen_l))

zen_file.close()
Но в консоли слипается последние/первые строки.

я понимаю, что дело в литерале, Но ХЗ куда его воткнуть
PM
Pro Mister*
277
 with open('zen.txt', 'r') as file: 
lines = file.readlines()
lines.reverse()
for line in lines:
print(line.strip())

print('\nПоследние две строки файла:')
print(lines[-2].strip())
print(lines[-1].strip())
Попробуйте вот так
НЧ
Нури Чорбаджи
321
Лучший ответ
Pro Mister* я пока еще не дошла до темы написания 'with open('zen.txt', 'r') as file: '

Поэтому пока не могу понять ваше решение
Нури Чорбаджи Принял, тогда по новой:
 file = open('zen.txt', 'r') 
lines = file.readlines()
file.close()

for line in reversed(lines):
print(line.strip())
Нури Чорбаджи Такой, теоретически, тоже может подойти:

 file = open("zen.txt", "r") 
lines = file.readlines()
lines.reverse()

for line in lines:
print(line.strip())

file.close()
Нури Чорбаджи Не за что)
Нури Чорбаджи Надеюсь как-то навел на мысль)
Вероятно у последней строки нету символа \n в конце, в у остальных - есть.
Убирай их у всех строк и выводи через \n строки. Либо к последней строке добавь его
Pro Mister* да, именно в этом причина. Но как ее добавить? Файл менять нельзя
Как вариант новую строку можно убрать при помощи функции strip.Результат.
ДЯ
Дачник Я
419
 zen_file = open('zen.txt', 'r') 

zen_list = [i_lines for i_lines in zen_file]
zen_file.close()

for line in zen_list[::-1]:
if line.endswith('\n'):
print(line, end='')
else:
print(line)
 Namespaces are one honking great idea -- let's do more of those! 
If the implementation is easy to explain, it may be a good idea.
If the implementation is hard to explain, it's a bad idea.
Although never is often better than *right* now.
Now is better than never.
Although that way may not be obvious at first unless you're Dutch.
There should be one-- and preferably only one --obvious way to do it.
In the face of ambiguity, refuse the temptation to guess.
Unless explicitly silenced.
Errors should never pass silently.
Although practicality beats purity.
Special cases aren't special enough to break the rules.
Readability counts.
Sparse is better than dense.
Flat is better than nested.
Complex is better than complicated.
Simple is better than complex.
Explicit is better than implicit.
Beautiful is better than ugly.
 with open('zen.txt', 'r') as file: 
for reverse_text in reversed(file.readlines()):
print(reverse_text.strip())
ZH
Zahir Huseyinli
153
Zahir Huseyinli
 with open('zen.txt', 'r') as file: 
lines = file.readlines()
for line in reversed(lines):
print(line.strip())
zen_file = open('zen.txt', 'r')
zen_reverse = zen_ file.read ().splitlines()
print('\n'.join(zen_reverse[::-1]))

zen_file.close()
zen_file = open('zen.txt', 'r')
print('\n'.join(zen_ file.read ().splitlines() [::-1]))
можно короче
Jasurbek Narziev
Jasurbek Narziev
120