AsapCancel
AsapCancel

Reputation: 87

Reversing lines of a text file through function in class

I am trying to make a class that receives file name in constructor and has function that reverses all the lines in that file.

class exampleOne:
    def __init__(self, fileName):
        self.fileName = fileName

    def reverse(self):
        file = open(self.fileName, "w")
        for value in list:
            file.write(value.rstrip() + "\n")
        file.close()

a = exampleOne("textExample.txt")
a.reverse()

Text file:
1.
2.
3.
The output i want in the existing file:
3.
2.
1.

But when I try running this, i get this error: "TypeError: 'type' object is not iterable".. Thanks in advance

Upvotes: 1

Views: 569

Answers (5)

Mahi
Mahi

Reputation: 21932

While you might think that you need a class here, you don't. Unless you got more code that you're not telling us about, the correct solution is to not use a class at all. Your class contains one string and has one method in it, there's nothing wrong with a simple function. It's in fact much better option compared to a class:

def reverse_lines(file_path):
    with open(file_path) as infile:
        lines = infile.readlines()
    with open(file_path, 'w') as outfile:
        outfile.writelines(lines[::-1])  # reversed(lines)

If your file does not end into a newline (\n), you will need to manually add the newline. Here's what the function might look like in its final form:

def reverse_lines(file_path):
    """
    Takes a path to a file as a parameter `file_path`
    and reverses the order of lines in that file.
    """

    # Read all the lines from the file
    with open(file_path) as infile:
        lines = infile.readlines()

    # Make sure there are more lines than one
    if len(lines) <= 1:
        return

    # If the file doesn't end into a newline character
    if not lines[-1].endswith('\n'):

        # Add it and remove the newline from the first (to be last) line
        lines[-1] += '\n'
        lines[1] = lines[1][:-1]

    # Reverse and output the lines to the file
    with open(file_path, 'w') as outfile:
        outfile.writelines(lines[::-1])

Upvotes: 1

Cyphase
Cyphase

Reputation: 12022

You don't need a class for this; a function will do just fine.

def reverse_lines_in_file(filepath):
    with open(filepath, 'r') as input_file:
        lines = input_file.readlines()

    lines.reverse()

    # If the new first line, which was the old last line,
    # doesn't end with a newline, add one.
    if not lines[0].endswith('\n'):
        lines[0] += '\n'

    with open(filepath, 'w') as output_file:
        for line in lines:
            output_file.write(line)


reverse_lines_in_file('textExample.txt')

There are better ways to do this, but as you seem to be a novice (nothing wrong with that :) ), I think this will do for now.

Upvotes: 1

AsapCancel
AsapCancel

Reputation: 87

Thanks for the help everyone, the code is working now. this is the final version that works perfectly

class exampleOne:
    def __init__(self, filePath):
        self.filePath = filePath

    def reverse(self):
        file = open(self.filePath, "r")
        list = file.readlines()
        file.close()

        list.reverse()

        file = open(self.filePath, "w")
        for value in list:
            file.write(value)
        file.close()

a = exampleOne("textExample.txt")
a.reverse()

Upvotes: 0

Batuhan B
Batuhan B

Reputation: 1855

I wrote this code, I think that this will be work for you. If you want you can write the output to the file.

class exampleOne:
    def __init__(self, fileName):
        self.fileName = fileName

    def reverse(self):

        with open('textExample.txt') as f:
            lines = f.readlines()    
        for i in lines:
            words = i.split()
            sentence_rev = " ".join(reversed(words))
            print sentence_rev
        f.close()
a = exampleOne("textExample.txt")
a.reverse()

Example txt file : 
Dummy Words
Dummy Words

Output:
Words Dummy
Words Dummy

Upvotes: 1

Greg Hewgill
Greg Hewgill

Reputation: 994021

This statement:

for value in list:

refers to something called list, but you don't have anything by that name in your program. Without a local definition, list refers to the built-in Python type list, which is not something you can use like that in a for loop.

It's usually a good idea to avoid redefining the names of built-in Python objects like list. In your case, you might use lines to represent a list of the lines in a file.

(You'll have to add code to actually read the lines from the file, too.)

Upvotes: 2

Related Questions