如何在python代码的第二列中对文件排序
这是我的文本文件。我想按升序对第二列进行排序。如何在python代码中对其进行排序 测试文件内容: 你可以如何在python代码的第二列中对文件排序,python,command-line,Python,Command Line,这是我的文本文件。我想按升序对第二列进行排序。如何在python代码中对其进行排序 测试文件内容: 你可以 # Read with open("filename.txt") as fic: lines = [line.rstrip().split() for line in fic] # read each line # Sort lines = sorted(lines, key=lambda x:x[1]) # Write again with open(&q
# Read
with open("filename.txt") as fic:
lines = [line.rstrip().split() for line in fic] # read each line
# Sort
lines = sorted(lines, key=lambda x:x[1])
# Write again
with open("filename.txt", "w") as fic:
fic.writelines([" ".join(line) + "\n" for line in lines]) # write each line
其他阅读方式
lines = []
with open("filename.txt") as fic:
for line in fic:
line = line.rstrip().split()
lines.append(line)
其他写作方式
with open("filename.txt", "w") as fic:
for line in lines:
fic.write(" ".join(line) + "\n")
将其作为数据帧读取,并使用
sort\u values()
对其进行排序。这回答了你的问题吗?1.读取文件内容。2.使用带有自定义键的sorted()
参数按升序对行进行排序。3.Re*(?)*写入结果。方法是否是对列进行排序的唯一选项?你提到的文本文件和我的问题一样。我不知道如何编写程序。有没有办法用python对列进行排序?你们可以考虑接受一个答案来奖励那个些帮助过你们的人,或者至少发表评论来解释遗漏了什么;)很好,谢谢。你能解释一下下面提到的两行吗?…lines=[line.rstrip().split()表示fic中的行]fic.writelines([''.join(line)+“\n”表示行中的行])@ChezhiyanSTR,只需读写每一行我知道这两行是读写的。我不知道那条线……你能把这两条线展开吗?
with open("filename.txt", "w") as fic:
for line in lines:
fic.write(" ".join(line) + "\n")