i have a sample csv file with me which contains some random numbers which are not sorted. i want to sort the data from the csv file and i have to write the sorted data into a new csv file. 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. 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.
thanks in advance.
You can use numpy
to deal with type conversion. 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.
The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.