简体   繁体   English

如何使用python对CSV文件进行排序并将排序后的数据写入新的CSV文件

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

i have a sample csv file with me which contains some random numbers which are not sorted. 我有一个示例csv文件,其中包含一些未排序的随机数。 i want to sort the data from the csv file and i have to write the sorted data into a new csv file. 我想对csv文件中的数据进行排序,我必须将排序后的数据写入新的csv文件中。 the problem is if i have a data like 问题是如果我有类似的数据

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

python is sorting based on the first digit only. python仅基于第一位进行排序。 if i print out the sorted data, i'm getting the below as output. 如果我打印出排序的数据,我将得到以下输出。

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

which is the sorting is performing based on the first digit. 这是根据第一个数字进行的排序。

and i want to write the sorted data to a new csv file. 我想将排序后的数据写入新的csv文件。

thanks in advance. 提前致谢。

You can use numpy to deal with type conversion. 您可以使用numpy来处理类型转换。 Something like this should work: 这样的事情应该起作用:

import numpy as np

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

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

Given that you have optional whitespace and commas this should work: 假设您有可选的空格和逗号,则应该可以使用:

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)

the above code worked for me. 上面的代码对我有用。 thanks for all the contribution. 感谢您的所有贡献。

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM