python - 根据第一列中的值对文件进行排序

标签 python file python-2.7 sorting

我有一个文件,其中包含多列(制表符分隔)中的结果(整数),开头的两行文本告诉我有关文件内容的信息,末尾的两行告诉我文件内容是否完整。

我有一个脚本可以根据第一列的值对文件进行排序,但想扩展它,以便它跳过文件的前两行和最后两行,同时也只打印出排序的第一列。我怎么能这样做呢?

这是我目前拥有的脚本:

file_name = "output1.dat"

new_file_name = "sorted_"+file_name
data = csv.reader(open(file_name),delimiter='\t')
sortedlist = sorted(data, key=lambda x:int(x[0]))
#now write the sorte result into new CSV file
with open(new_file_name, "wb") as f:
    fileWriter = csv.writer(f, delimiter=',')
    for row in sortedlist:
        fileWriter.writerow(row)

它会被文本行绊倒,因为它们不包含任何列。

最佳答案

这应该跳过前两行和最后两行:

sortedlist = sorted(list(data)[2:-2], key=lambda x:int(x[0]))

只写第一列:

fileWriter.writerow(row[:1])

完整脚本:

file_name = "output1.dat"

new_file_name = "sorted_"+file_name
data = csv.reader(open(file_name),delimiter='\t')
sortedlist = sorted(list(data)[2:-2], key=lambda x:int(x[0]))
#now write the sorte result into new CSV file
with open(new_file_name, "wb") as f:
    fileWriter = csv.writer(f, delimiter=',')
    for row in sortedlist:
        fileWriter.writerow(row[:1])

关于python - 根据第一列中的值对文件进行排序,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/35086560/

相关文章:

python - 在 Tkinter 中显示 matplotlib

macos - 将 x 行从大文件复制到 mac 上的新文件

c++ - 将数据保存在 std::vector 或 .txt 文件中是否更快?

python - 从 C++ 调用 Python 脚本并使用其输出

python - 在 Hadoop Streaming 作业中写入 Parquet 输出

python - pip 从 python 中自己的(命名空间)包安装子包

python - 在 Django/Python 中复制或克隆一个对象实例

python - 文件大小是否会影响 python 中写入的性能

python - 最Pythonic的方式来填充小数点左边的 float

python-2.7 - matplotlib.pyplot 中的阴影不确定性/误差区域