Skip to content

Instantly share code, notes, and snippets.

@pareksha
Created January 8, 2019 11:16
Show Gist options
  • Save pareksha/96317b47f0f4c5414de4e1b8401affc0 to your computer and use it in GitHub Desktop.
Save pareksha/96317b47f0f4c5414de4e1b8401affc0 to your computer and use it in GitHub Desktop.
Easy write on csv file using python (with simple file open and file write commands)
# Make directory if it doesn't exist
directory = 'media/csvs/'
if not os.path.exists(directory):
os.makedirs(directory)
path = directory + 'student_data.csv'
csvFile = open(path, 'w')
csvFile.write('Name,Contact Number,email\n')
# Iterate through queryset or list and do the following for each iteration
csvFile.write(name.replace(',', '|') + ',' + contact_number.replace(',', '|') + ',' + email.replace(',', '|') + '\n')
# Don't forget to close the file, otherwise changes will not be saved
csvFile.close()
Sign up for free to join this conversation on GitHub. Already have an account? Sign in to comment