thesctt
thesctt

Reputation: 21

Exporting variable to CSV file in python

I am in the process of creating a simple random number generator in python for a school project. This is what I have so far:

import random

amnt = input('Please enter the amount of numbers you would like:')
for i in range(0,amnt):


          x = random.randint(0,100000000)
          print x

This has the desired result, it generates a set amount of random numbers based on the user input. The problem I need to solve now is how to export the numbers generated into one CSV file so that they can be analysed. I believe that the CSV module needs to be imported and implemented but I am not sure how to do this. I am trying to analyze the effectiveness of the random module in order to write an essay so being able to use excel to sort and filter the numbers would be very helpful. Any changes or modifications to the code would also be very much appreciated.

Upvotes: 1

Views: 22464

Answers (3)

Vidit Gang
Vidit Gang

Reputation: 41

You just need a one line code to convert a variable to csv format. Let me know if this does not work. If the code works for you please rate the answer.

x.to_csv('file_name.csv')

Upvotes: 4

Robᵩ
Robᵩ

Reputation: 168716

No, you don't really the csv module for a case this simple. You just need to create a text file in which the values are separated by commas. (Hence the name, Comma-Separated Values, CSV).

Try this:

import random

amnt = int(raw_input('Please enter the amount of numbers you would like:'))
data = (random.randint(0,100000000) for _ in range(amnt))
data = (str(datum) for datum in data)
data = ','.join(data) + '\n'
with open("random.csv", "w") as fp:
    fp.write(data)

Upvotes: 2

DJanssens
DJanssens

Reputation: 20789

import random
import csv

amnt = input('Please enter the amount of numbers you would like:')
ofile  = open('ttest.csv', "wb")
writer = csv.writer(ofile, delimiter=',')
for i in range(0,amnt):
    x = random.randint(0,100000000)
    writer.writerow([x])
ofile.close()

Might be a quick solution to your problem. writerow will write a row to your csv. Since you want to open it in excel I wrote one number/row, so you can order it based on the column.

However, you could also sort the numbers programatically without having to use excel. As some already mentioned CSV is especially aimed for storing data structures.

More info can be found in the csv module documentation

Upvotes: 0

Related Questions