For an assignment I have to write some data to a .csv
file. I have an implementation that works using Python's csv
module, but apparently I am not supposed to use any imported libraries...
So, my question is how I could go about doing so? I am no expert when it comes to these things, so I am finding it difficult to find a solution online; everywhere I look import csv
is being used.
CodePudding user response:
Since csv
stands for comma-separated values, you can create a file with the regular I/O built-in function that ends with .csv
like:
f = open("demofile.csv", "w")
And then write to it:
f.write("1, 2, 3 ,4, 5\n 6, 7, 8, 9, 10")
Where each cell is separated by comma, and each row is separated by \n
.
The result will look like this in MS Excel
:
CodePudding user response:
To create or open a file just use:
(Second Parameter "w" -> Overwrite the file, "a" -> append to file, "r" -> read file)
file = open("test.csv", "w")
Now you can write data to that file by using the write function:
file.write("surname,name,age,address\n")
When you are finished with writing to the file use
file.close()
CodePudding user response:
I guess that the point of your assignment is not to have some else to do it for you online. So a few hints:
- organise your data per row.
- iterates through the rows
- look at concatenating strings
- do all above while iterating to a text file per line