Exporting variable to CSV file in python - 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.

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')

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)

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

Related

How to write in a specific cell in a CSV file?

I have an asignment in which I need to imput random grades of different students in a csv file using Python 3, and get the average of each student(the average thing and how to get the random grades, I know how to do it), the thing is that I don't know how to write the grades on those specific columns and rows(highlighted ones).
Highlighted area is the space in which I need to write random grades:
Is there anyway that this can be done? I'm fairly new to programming and Python 3, and as far as I've read, specifics cells can't be changed using normal means.
csv module doesn't have functions to modify specific cells.
You can read rows from original file, append grades and write modified rows to new file:
import random
import csv
inputFile = open('grades.csv', 'r')
outputFile = open('grades_out.csv', 'w')
reader = csv.reader(inputFile)
writer = csv.writer(outputFile)
for row in reader:
grades = row.copy()
for i in range(5):
grades.append(random.randint(1, 5))
writer.writerow(grades)
inputFile.close()
outputFile.close()
Then you can delete original file and rename new file (it is not good to read the whole original file to a variable, close it, open it again in writing mode and then write data, because it can be big).

Grab values from seperate csv file and replace the values of columns in a pipe delimited file

Trying to whip this out in python. Long story short I got a csv file that contains column data i need to inject into another file that is pipe delimited. My understanding is that python can't replace values, so i have to re-write the whole file with the new values.
data file(csv):
value1,value2,iwantthisvalue3
source file(txt, | delimited)
value1|value2|iwanttoreplacethisvalue3|value4|value5|etc
fixed file(txt, | delimited)
samevalue1|samevalue2| replacedvalue3|value4|value5|etc
I can't figure out how to accomplish this. This is my latest attempt(broken code):
import re
import csv
result = []
row = []
with open("C:\data\generatedfixed.csv","r") as data_file:
for line in data_file:
fields = line.split(',')
result.append(fields[2])
with open("C:\data\data.txt","r") as source_file, with open("C:\data\data_fixed.txt", "w") as fixed_file:
for line in source_file:
fields = line.split('|')
n=0
for value in result:
fields[2] = result[n]
n=n+1
row.append(line)
for value in row
fixed_file.write(row)
I would highly suggest you use the pandas package here, it makes handling tabular data very easy and it would help you a lot in this case. Once you have installed pandas import it with:
import pandas as pd
To read the files simply use:
data_file = pd.read_csv("C:\data\generatedfixed.csv")
source_file = pd.read_csv('C:\data\data.txt', delimiter = "|")
and after that manipulating these two files is easy, I'm not exactly sure how many values or which ones you want to replace, but if the length of both "iwantthisvalue3" and "iwanttoreplacethisvalue3" is the same then this should do the trick:
source_file['iwanttoreplacethisvalue3'] = data_file['iwantthisvalue3]
now all you need to do is save the dataframe (the table that we just updated) into a file, since you want to save it to a .txt file with "|" as the delimiter this is the line to do that (however you can customize how to save it in a lot of ways):
source_file.to_csv("C:\data\data_fixed.txt", sep='|', index=False)
Let me know if everything works and this helped you. I would also encourage to read up (or watch some videos) on pandas if you're planning to work with tabular data, it is an awesome library with great documentation and functionality.

Saving a list of UUID numbers to a .csv file in python

I am trying to create a .csv file of UUID numbers. I see how to make a single UUID number in python but can't get the correct syntax to make 50 numbers and save them to a .csv file. I've googled and found many ways to create .csv files and how to use For loop but none seem to pertain to this particular application. Thank you for any help.
Just combine a csv writer with an uuid generator
import csv
import uuid
with open('uuids.csv', 'w') as csvfile:
uuidwriter = csv.writer(csvfile)
for i in range(50):
uuidwriter.writerow([uuid.uuid1()])
a csv is basically a text file, and since yours have only one column you won't need separators :
import uuid
with open('uuids.csv', 'w') as f:
f.writelines(str(uuid.uuid1()) + "\n" for i in range(50))

split excel sheet for every nrows using python

I have an excel file with more than 1 million rows. Now i need to split that for every n rows and save it in a new file. am very new to python. Any help, is much appreciated and needed
As suggested by OhAuth you can save the Excel document to a csv file. That would be a good start to begin the processing of you data.
Processing your data you can use the Python csv library. That would not require any installation since it comes with Python automatically.
If you want something more "powerful" you might want to look into Pandas. However, that requires an installation of the module.
If you do not want to use the csv module of Python nor the pandas module because you do not want to read into the docs, you could also do something like.
f = open("myCSVfile", "r")
for row in f:
singleRow = row.split(",") #replace the "," with the delimiter you chose to seperate your columns
print singleRow
> [value1, value2, value3, ...] #it returns a list and list comprehension is well documented and easy to understand, thus, further processing wont be difficult
However, I strongly recommend looking into the moduls since they handle csv data better, more efficient and on 'the long shot' save you time and trouble.

Import csv into python and sum the row of numbers

I have started learning python with great enthusiasm and managed to get through the procedures, functions and bit of lists. And feel ready to take the learning forward by building a useful application.
I would like the user to export an excel file into csv with just one row of numbers, some of them negative, positive and zeros. And want to calculate the average of positive numbers and average of negative numbers.
The calculating bit isn't the problem, its the importing csv bit. I've been reading the python documentation but looked confusing.
Please get me started on importing a csv file and summing the row of numbers. Thank you!
This should get you started.
import csv
with open("file.csv", "rb") as ins:
for row in csv.reader(ins):
print sum(map(int, row))
The with statement is a way to make this exception-safe. In most cases, the following is good enough:
import csv
ins = open("file.csv", "rb")
for row in csv.reader(ins):
print sum(map(int, row))
ins.close()
The above solutions don't work with Python 3. Instead, try this:
import csv
with open("test.csv", "r") as ins:
for row in csv.reader(ins):
print(sum(map(int, row)))

Categories

Resources