I have to write a program that will reverse the letters of the words in a file.
For example, if the file contains the words:
snow
tree
star
wreath
It would change them into:
wons
eert
rats
htaerw
Once that is done, I have to write a new file that will write them in reverse order so it would look like:
htaerw
rats
eert
wons
Here is my code:
def reverse(string):
#empty list for string
word = []
#for each letter in the string obtain the corresponding opposite number
#first letter to last letter, second letter to second last letter, etc...
for letter in range(len(string)-1, -1, -1):
word.append(string[letter])
#create main() function
def main():
#open file and read words in each line
input_file = open("words.txt", "r")
word_file = input_file.readlines()
#empty list for the words in the file, after their letters have been reversed
reversed_list = []
for word in range(len(word_file)):
reverse_word = reverse(word_file[word])
reversed_list.append(reverse_word)
#create new file of the reversed words IN REVERSED ORDER!
reverse_file = open("reverse.txt","w")
reverse_file.writelines(reversed_list)
reverse_file.close()
main()
How can I edit the main function to reverse the order of the words without using the built-in .reverse() function?
One liners (since we all love them):