Write CSV with Django
To write files, the same scheme is used as the previous codes, but the files must be opened in writing mode and the writer() function must be used instead of the reader() function; the file to write does not have to exist (in the following example, to avoid deleting the previous file, the file to be referenced is placed as “Book2”):
def csv_write(request):
filename="documents/Book2.csv"
try:
file = open(filename, 'w', newline="")
#print(type(file))
csv_writer = csv.writer(file, delimiter=",")
# print(type(csv_writer))
csv_writer.writerow(["Movie 1","Movie 2", "Movie 3"])
csv_writer.writerow(["Avengers","Batman", "Superman"])
csv_writer.writerow(["Avengers 3","Batman 2", "Other"])
csv_writer.writerow(["Avengers 4","Batman", "Spiderman"])
file.close()
except (IOError) as error:
print("Error {}".format(error))
return render(request, 'csv.html')
Being in writing mode, a structure must be presented which we want to replicate in the file; In this case, they would be lists, which, as we saw in the reading examples, are the formats returned when reading the files.
To write a list, the writerow() function is used, you can also use the writerows() function to write multiple lists:
data=[
["Name","Surname","Age"],
["Jon","Snow",33],
["Daenerys","Targaryen",25],
["Tyrion","Lannister",40],
["Jaime","Lannister",35],
["Cersei","Lannister",36]
]
writer.writerows(data)
newline option is also used as an empty, with this, we avoid that when a new column is going to be written, it places a space between records; without defining the newline:
Movie 1;Movie 2;Movie 3
Avengers;Batman;Superman
Avengers 3;Batman 2;Other
Definiendo el newline:
Pelicula 1;Pelicula 2;Pelicula 3
Avengers;Batman;Superman
Avengers 3;Batman 2;Otro
Su ruta:
csvs\urls.py
urlpatterns = [
// ***
path(csv_write, views.csv_write),
And we will have as output, a file with the format that we specified above:
documents\Libro2.csv
Pelicula 1;Pelicula 2;Pelicula 3
Avengers;Batman;Superman
Avengers 3;Batman 2;Otro
Avengers 4;Batman;Spiderman
- Andrés Cruz
Develop with Laravel, Django, Flask, CodeIgniter, HTML5, CSS3, MySQL, JavaScript, Vue, Android, iOS, Flutter