代码之家  ›  专栏  ›  技术社区  ›  rabidmachine9

在python中对文本文件的内容排序后文件中的空行

  •  11
  • rabidmachine9  · 技术社区  · 15 年前

    我有一个对文本文件内容排序的小脚本

    # The built-in function `open` opens a file and returns a file object.
    
    # Read mode opens a file for reading only.
    try:
        f = open("tracks.txt", "r")
    
    
        try:
            # Read the entire contents of a file at once.
           # string = f.read() 
            # OR read one line at a time.
            #line = f.readline()
            # OR read all the lines into a list.
            lines = f.readlines()
            lines.sort()
            f.close()
            f = open('tracks.txt', 'w')
            f.writelines(lines) # Write a sequence of strings to a file
        finally:
            f.close()
    except IOError:
        pass
    

    唯一的问题是,文本每次排序时都显示在文本文件的底部…

    我猜想它也对空行进行排序……有人知道为什么吗?

    也许你能提出一些如何避免这种情况发生的建议吗?

    提前谢谢

    3 回复  |  直到 9 年前
        1
  •  24
  •   John Machin Santi    15 年前

    从文本文件读取的“空”行在python中用只包含换行符(“\n”)的字符串表示。您可能还希望避免“数据”仅由空格、制表符等组成的行(“空白”)。str.strip()方法允许检测这两种情况(换行符是空白)。

    f = open("tracks.txt", "r")
    # omit empty lines and lines containing only whitespace
    lines = [line for line in f if line.strip()]
    f.close()
    lines.sort()
    # now write the output file
    
        2
  •  6
  •   Mark McEahern    15 年前

    这是进行基于测试的开发的绝佳机会(见下文)。一些观察结果:

    1. 在下面的示例中,我省略了从文件读取和写入文件的方面。在我看来,这对这个问题并不重要。

    2. 我假设您希望去掉尾随的换行符并省略空白行。如果没有,你需要调整。(但您将拥有断言/确认预期行为的框架。)

    3. 我同意上面的chryss,您通常不需要在python的try块中反射性地包装东西。我相信这是来自Java的反模式(强迫它)。

    不管怎样,这里是测试:

    import unittest
    
    def sort_lines(text):
        """Return text sorted by line, remove empty lines and strip trailing whitespace."""
        lines = text.split('\n')
        non_empty = [line.rstrip() for line in lines if line.strip()]
        non_empty.sort()
        return '\n'.join(non_empty)
    
    class SortTest(unittest.TestCase):
    
      def test(self):
        data_to_sort = """z some stuff
    c some other stuff
    
    
    d more stuff after blank lines
    b another line
    a the last line"""
    
        actual = sort_lines(data_to_sort)
        expected = """a the last line
    b another line
    c some other stuff
    d more stuff after blank lines
    z some stuff"""
    
        self.assertEquals(actual, expected, "no match!")
    
    unittest.main()
    
        3
  •  4
  •   chryss    15 年前

    它对空白行排序的原因是它们在那里。空行是一个空字符串,后跟\n(或\r\n或\r,具体取决于操作系统)。完全可以分类。

    我要注意的是,“尝试:”嵌套到“尝试…”中。除了“block有点难看,为了时尚起见,我会在阅读后关闭文件。