【问题标题】:Sort Lines from File with Numbers使用数字对文件中的行进行排序
【发布时间】:2021-04-18 17:03:18
【问题描述】:

我再次需要你的帮助,我不知道该怎么做

我有一个文件,它看起来像这样:

file.txt:

005-test1
039-test1
008-test1
009-ttest1
003-test1 97F199F
015-test1 C7264DF9
007-test1 5AD753A0
059-test1 CF4BFD2F

我想让文件按数字升序排序,这样在这里看起来像这样

003-test1 97F199F
005-test1
007-test1 5AD753A0
008-test1
009-ttest1
015-test1 C7264DF9
039-test1
059-test1 CF4BFD2F

不幸的是,我不知道该怎么做

【问题讨论】:

标签: python-3.x


【解决方案1】:

我相信以下 sn-p 可以满足您的要求:

def sort_lines(inputfile, outputfile):
    lines = open(inputfile).readlines()
    with open(outputfile, "w") as out:
        out.write("".join(sorted(lines)))

sort_lines("file.txt", "outputfile.txt")

我们使用的地方:

  • open函数打开输入输出文件,
  • readlines 从打开的文件中读取每一行,
  • sorted 函数对行进行排序。

【讨论】:

    【解决方案2】:
    dic = {}
    with open("file.text", "r") as f:
        for line in f:
            number = int(line.split("-")[0])
            dic[number] = line
    for x in sorted(dic):
        print(dic.get(x))
    
    
        
    

    【讨论】:

      猜你喜欢
      • 2020-10-09
      • 2018-12-17
      • 1970-01-01
      • 2012-11-01
      • 2012-04-01
      • 2012-05-23
      • 2021-11-15
      • 1970-01-01
      • 2016-08-06
      相关资源
      最近更新 更多