Home > Software engineering >  Is there a way to reverse the order of lines within a text file using a function in python?
Is there a way to reverse the order of lines within a text file using a function in python?

Time:04-18

def encrypt():
  while True:
    try:
        userinp = input("Please enter the name of a file: ")
        file = open(f"{userinp}.txt", "r")
        break  
    except:
      print("That File Does Not Exist!")
  second = open("encoded.txt", "w")
  
  
  for line in file:
    reverse_word(line)




def reverse_word(line):
  data = line.read()
  data_1 = data[::-1]
  print(data_1)
  return data_1

encrypt()











I'm currently supposed to make a program that encrypts a text file in someway, and one method that i'm trying to use is reversing the sequence of the lines in the textfile. All of my other functions already made, utilize the "for line in file", where "line" is carried over to each separate function, then changed for the purpose of encryption, but when trying to do the same thing here for reversing the order of the lines in the file, I get an error

"str" object has no attribute "read"

I've tried using the same sequence as I did down below, but instead carrying over the file, which works, but I want to have it so that it can work when I carry over individual lines from the file, as is, with the other functions that I have currently (or more simply put, having this function inside of the for loop).

Any Suggestions? Thanks!

CodePudding user response:

Are you trying to reverse the order of the lines or the order of the words in each line?

Reversing the lines can be done by simply reading the lines and using the built-in reverse function:

lines = fp.readlines()
lines.reverse()

If you're trying to reverse the words (actual words, not just the string of characters in each line) you're going to need to do some regex to match on word boundaries.

Otherwise, simply reversing each line can be done like:

lines = fp.readlines()
for line in lines:
    chars = list(line)
    chars.reverse()

CodePudding user response:

I think the bug you're referring to is in this function:

def reverse_word(line):
  data = line.read()
  data_1 = data[::-1]
  print(data_1)
  return data_1

You don't need to call read() on line because it's already a string; read() is called on file objects in order to turn them into strings. Just do:

def reverse_line(line):
    return line[::-1]

and it will reverse the entire line.

If you wanted to reverse the individual words in the line, while keeping them in the same order within the line (e.g. turn "the cat sat on a hat" to "eht tac tas no a tah"), that'd be something like:

def reverse_words(line):
    return ' '.join(word[::-1] for word in line.split())

If you wanted to reverse the order of the words but not the words themselves (e.g. turn "the cat sat on a hat" to "hat a on sat cat the"), that would be:

def reverse_word_order(line):
    return ' '.join(line.split()[::-1])
  • Related