Article Categories
- All Categories
-
Data Structure
-
Networking
-
RDBMS
-
Operating System
-
Java
-
MS Excel
-
iOS
-
HTML
-
CSS
-
Android
-
Python
-
C Programming
-
C++
-
C#
-
MongoDB
-
MySQL
-
Javascript
-
PHP
-
Economics & Finance
Selected Reading
Python - Display the Contents of a Text File in Reverse Order?
We will display the contents of a text file in reverse order. Python provides several methods to reverse text content, including slicing and looping approaches.
Using String Slicing
The most Pythonic way to reverse text content is using slice notation with a negative step ?
# Create sample text content
text_content = "This is it!"
# Write to file first
with open("sample.txt", "w") as file:
file.write(text_content)
# Read and reverse the file content
with open("sample.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("Original data =", my_data)
print("Reversed data =", rev_data)
Original data = This is it! Reversed data = !ti si sihT
Using Manual Looping
You can also reverse text content by iterating through characters manually ?
# Create sample text content
text_content = "This is it!"
# Write to file first
with open("sample.txt", "w") as file:
file.write(text_content)
# Read file content
with open('sample.txt', 'r') as my_data:
content = my_data.read()
# Reverse the data using manual loop
length = len(content)
rev_data = ''
while length >= 1:
rev_data = rev_data + content[length - 1]
length = length - 1
print("Original data =", content)
print("Reversed data =", rev_data)
Original data = This is it! Reversed data = !ti si sihT
Using reversed() Function
Python's built-in reversed() function provides another clean approach ?
# Create sample text content
text_content = "This is it!"
# Write to file first
with open("sample.txt", "w") as file:
file.write(text_content)
# Read and reverse using reversed() function
with open("sample.txt", "r") as myfile:
my_data = myfile.read()
# Join reversed characters
rev_data = ''.join(reversed(my_data))
print("Original data =", my_data)
print("Reversed data =", rev_data)
Original data = This is it! Reversed data = !ti si sihT
Comparison
| Method | Readability | Performance | Best For |
|---|---|---|---|
Slicing [::-1]
|
High | Fastest | Simple text reversal |
| Manual Loop | Low | Slowest | Learning purposes |
reversed() |
High | Good | Functional programming style |
Conclusion
Use string slicing [::-1] for the most efficient text reversal. The reversed() function offers good readability, while manual looping helps understand the underlying process.
Advertisements
