【问题标题】:Open a text file,sort the text file and then save it using Python打开一个文本文件,对文本文件进行排序,然后使用 Python 保存
【发布时间】:2017-09-05 14:42:24
【问题描述】:

我从Stackoverflow 中找到了以下 Python 代码,它打开了一个名为 sort.txt 的文件,然后对文件中包含的数字进行排序。

代码运行完美。我想知道如何将排序后的数据保存到另一个文本文件中。每次我尝试时,保存的文件都显示为空。 任何帮助,将不胜感激。 我希望将保存的文件称为sorted.txt

with open('sort.txt', 'r') as f:
    lines = f.readlines()
numbers = [int(e.strip()) for e in lines]
numbers.sort()

【问题讨论】:

    标签: python-3.x


    【解决方案1】:

    您可以将其与f.write() 一起使用:

    with open('sort.txt', 'r') as f:
        lines = f.readlines()
    
    numbers = [int(e.strip()) for e in lines]
    numbers.sort()
    
    with open('sorted.txt', 'w') as f: # open sorted.txt for writing 'w'
        # join numbers with newline '\n' then write them on 'sorted.txt'
        f.write('\n'.join(str(n) for n in numbers))
    

    输入(sort.txt):

    1
    -5
    46
    11
    133
    -54
    8
    0
    13
    10
    

    输出(sorted.txt):

    -54
    -5
    0
    1
    8
    10
    11
    13
    46
    133
    

    【讨论】:

      【解决方案2】:

      <file object>.writelines()方法:

      with open('sort.txt', 'r') as f, open('output.txt', 'w') as out:
          lines = f.readlines()
          numbers = sorted(int(n) for n in lines)
          out.writelines(map(lambda n: str(n)+'\n', numbers))
      

      【讨论】:

        【解决方案3】:

        从当前文件中获取排序后的数据并保存到变量中。 以写入模式('w')打开新文件,并将保存的变量中的数据写入文件。

        【讨论】:

          猜你喜欢
          • 2023-04-09
          • 1970-01-01
          • 2016-07-01
          • 1970-01-01
          • 2011-10-15
          • 1970-01-01
          • 1970-01-01
          • 1970-01-01
          相关资源
          最近更新 更多