簡體   English   中英

如何使用python對CSV文件進行排序並將排序后的數據寫入新的CSV文件

[英]How to sort a csv file using python and write the sorted data to the new csv file

我有一個示例csv文件,其中包含一些未排序的隨機數。 我想對csv文件中的數據進行排序,我必須將排序后的數據寫入新的csv文件中。 問題是如果我有類似的數據

 3,
65,
20,
21,
19,
34,
8,
0,
22

python僅基於第一位進行排序。 如果我打印出排序的數據,我將得到以下輸出。

['0'], ['19'], ['20'], ['21'], ['22'], ['3'], ['34'], ['65'], ['8']

這是根據第一個數字進行的排序。

我想將排序后的數據寫入新的csv文件。

提前致謝。

您可以使用numpy來處理類型轉換。 這樣的事情應該起作用:

import numpy as np

arr = np.genfromtxt('in.csv', delimiter=',')
arr.sort()

np.savetxt('out.csv', arr, delimiter=',')

假設您有可選的空格和逗號,則應該可以使用:

with open('in.csv') as infile, open(out.csv) as outfile:
    data = infile.readlines() #read data into list line by line
    nums = [''.join([c for c in i if c.isdigit()]) for i in data] #extract only the numbers from lines
    result = sorted(nums, key=int) #sort the numbers by their integer value ascending (default)
    outfile.write(',\n'.join(result)) #write result to file adding `,\n` to end of each number - \n being the newline
import csv


with open('sample.csv') as file:
    reader = csv.reader(file)
    i = 0
    new_data = []
        for row in reader:
            if(row[0]!='' and row[0].isdigit()):
                new_data.append(row[0])
                new_data.sort(key=int)
                print(new_data)
with open('newfile.csv', 'w') as newfile:
    writer = csv.writer(newfile)
    writer.writerow(new_data)

上面的代碼對我有用。 感謝您的所有貢獻。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM