Python 按字符串中的负值对文件中的行进行排序

Python 按字符串中的负值对文件中的行进行排序,python,Python,我有以下几行的文件 channel: 6372225 rxLev: -58 name: Right channel: 6372235 rxLev: -52 name: left channel: 4372225 rxLev: -51 name: left channel: 1372225 rxLev: -22 name: left channel: 6371115 rxLev: -33 name: Right channel: 6376665 rxLev: -40 name: left

我有以下几行的文件

channel: 6372225 rxLev: -58 name: Right
channel: 6372235 rxLev: -52 name: left 
channel: 4372225 rxLev: -51 name: left 
channel: 1372225 rxLev: -22 name: left 
channel: 6371115 rxLev: -33 name: Right
channel: 6376665 rxLev: -40 name: left 
channel: 6322225 rxLev: -60 name: left 
channel: 6112225 rxLev: -80 name: up

如何使用python按照rxLev值对同一文件中的这些行进行排序?

假设文件名为
stackoverflow.txt

with open('stackoverflow.txt', 'r') as f:
  sorted_list = sorted([item.split(" ") for item in f.readlines()], 
                        key=lambda x: float(x[3]))  # or int

with open('stackoverflow.txt', 'w') as f:
  for sublist in sorted_list:
    f.write(" ".join(word for word in sublist))

您只需在删除旧内容时读取内容、对其进行排序并将其写回即可:

with open('your_file.txt', 'r+') as f:
    sorted_contents =  ''.join(sorted(f.readlines(), key = lambda x: int(x.split(' ')[3])))
    f.seek(0)
    f.truncate()
    f.write(sorted_contents)

与打开一次阅读,然后再打开一次写作相比,原子化操作也能使其更具抗错误性

这是否回答了您的问题?