1

I have this code which generates a random number. I want it to save the random number on a new line/row every time it is run(the code).

I tried adding newLine and newRow but it did not work.

import csv import random newFile = open("random.csv",'w',newline='') newWriter = csv.writer(newFile, dialect='excel') newRow = [] case_number = random.randint(0,1000000000) print("Your problem has been stored. We have allocated a case number which will be sent off to a technician. Please take a note of your case number: ", str(case_number)) newRow.append(case_number) newWriter.writerow(newRow) newFile.close() 

And how can I shorten this piece of code?

Any help will be appreciated.

Thank you!

2
  • "it did not work". Why? What happened? Commented May 9, 2016 at 12:05
  • 3
    Open the the file in append mode 'a' instead of 'w'. Commented May 9, 2016 at 12:06

1 Answer 1

1

I made some minor modification to the original code.

replaced "w" with "a" (append) as suggested by @ JRodDynamite - in order to save the previous data in the file, and append the new data

Added "with" - as suggested by @Display Name - which ensure that a resource is "cleaned up" when the code that uses it finishes running.

Defined the case_number to be string (cast of the random int).

I continued using CSV writer as used by @Jason Cole.

I removed the newRow and the append.

import csv import random with open("random.csv",'a') as newFile: newWriter = csv.writer(newFile, dialect='excel') case_number = str(random.randint(0,1000000000)) print("Your problem has been stored. We have allocated a case number which will be sent off to a technician. Please take a note of your case number: ", case_number) newWriter.writerow([case_number]) newFile.close() 
Sign up to request clarification or add additional context in comments.

2 Comments

@Display Name - Thanks for the comment! added "with"
Some explanation would be helpful as well, otherwise this will become reality: theallium.com/engineering/…

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.