通过类中的函数反转文本文件的行

时间:2015-08-09 23:25:55

标签: python oop reverse

我正在尝试创建一个在构造函数中接收文件名的类,并且具有反转该文件中所有行的函数。

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.

但是当我尝试运行它时,我收到此错误: " TypeError:' type'对象不可迭代" ..提前致谢

5 个答案:

答案 0 :(得分:2)

本声明:

for value in list:

指的是名为list的内容,但您的程序中没有该名称的内容。如果没有本地定义,list会引用内置的Python类型list,这不是for循环中可以使用的类型。

避免重新定义内置Python对象(如list)的名称通常是个好主意。在您的情况下,您可以使用lines来表示文件中的行列表。

(您必须添加代码以实际读取文件中的行。)

答案 1 :(得分:1)

我写了这段代码,我认为这对你有用。如果需要,可以将输出写入文件。

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

答案 2 :(得分:1)

你不需要上课;一个函数就可以了。

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')

有更好的方法可以做到这一点,但是因为你似乎是一个新手(没有错:)),我认为现在这样做。

答案 3 :(得分:1)

虽然你可能认为你需要在这里上课,但你不会。除非你得到更多你没有告诉我们的代码,否则正确的解决办法就是不要使用任何类。 你的类包含一个字符串,其中有一个方法,一个简单的函数没有错。事实上,与班级相比,它实际上是更好的选择:

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)

如果您的文件未以换行符(\n)结尾,则需要手动添加换行符。这是函数最终形式的样子:

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])

答案 4 :(得分:0)

感谢大家的帮助,代码现在正在运行。这是完美运行的最终版本

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()