Python - Display contents of text file in reverse order

王林
Release: 2023-08-31 10:01:01
forward
971 people have browsed it

We will display the contents of the text file in reverse order. To do this, we first create a text file amit.txt

with the following content

Python - 以相反的顺序显示文本文件的内容

Display the contents of a text file in reverse order by slicing

Example

Now let us read the contents of the above files in reverse order -

# The file to be read
with open("amit.txt", "r") as myfile:
   my_data = myfile.read()

# Reversing the data by passing -1 for [start: end: step]
rev_data = my_data[::-1]

# Displaying the reversed data
print("Reversed data = ",rev_data)
Copy after login

Output

Reversed data = !tisisihT
Copy after login
Copy after login

Display the contents of the text file in reverse order through a loop

Example

# Opening the file to read
my_data = open('amit.txt','r')

# reversing the data
for myLine in my_data:
   l = len(myLine)
   rev_data = ''

while(l>=1):
   rev_data = rev_data + myLine[l-1]
   l=l-1
print("Reversed data = ",rev_data) # Displaying the reversed data
Copy after login

Output

Reversed data = !tisisihT
Copy after login
Copy after login

The above is the detailed content of Python - Display contents of text file in reverse order. For more information, please follow other related articles on the PHP Chinese website!

source:tutorialspoint.com
Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn
Popular Tutorials
More>
Latest Downloads
More>
Web Effects
Website Source Code
Website Materials
Front End Template
About us Disclaimer Sitemap
php.cn:Public welfare online PHP training,Help PHP learners grow quickly!