【发布时间】:2022-01-10 18:49:04
【问题描述】:
我正在尝试按每行中的第一个数字对 .txt 文件中的行进行排序。sample text file 我还想将每行中的第二个数字移到每行的末尾。这是我到目前为止的内容,但由于某种原因,这些行没有按两个文件之间的数字排序。
#combine files
filenames = ['detections_mandatory.txt','detections_other.txt']
lines = []
for names in filenames:
with open(names) as infile:
for line in infile:
lines.append(line)
#write list out to new file
with open("detections.txt", "w") as det:
det.write(''.join(sorted(lines, key=lambda x: int(x.strip()))))
【问题讨论】:
-
您的代码对我有用。我唯一的问题是在对元素进行排序后,它不会在其后添加
\n。我认为这可以通过添加到join和\n来完成。但无法重现您所说的问题 -
我最终只是关闭并重新打开了我正在使用的所有文件,问题就自行解决了。我仍然不确定是否将每行中的第二个数字移到行尾
标签: python file sorting text script