Rigel Panaligan
Rigel Panaligan

Reputation: 1

How to name my file based on a randomly generated number?

I want to name my file as the student number comes up.

Here is the code:

import random
SNumber=random.randint(199999,999999)
print(SNumber)
writefile=open("studentNumberhere.txt","a")
writefile.write(SNumber)
writefile.close()

If the code runs and it generates the number: 123456

The filename would be 123456.txt

And if I generate another number, there will be another file appearing on my folder.

Upvotes: 0

Views: 50

Answers (2)

Sinto
Sinto

Reputation: 3997

writefile = open(str(SNumber)+'.txt','a')

If the file does not exists, open(name,'r+') will fail.

You can use open(name, 'w'), which creates the file if the file does not exist, but it will truncate the existing file.

Alternatively, you can use open(name, 'a'); this will create the file if the file does not exist, but will not truncate the existing file.

import sys
import random
def create():
SNumber=random.randint(199999,999999)
try:
    writefile = open(str(SNumber)+'.txt','a')
    writefile.write(SNumber)
    writefile.close()
except:
    print("Error occurred.")
    sys.exit(0)

create()

Upvotes: 0

Yarn
Yarn

Reputation: 84

import random
SNumber=random.randint(199999,999999)
print(SNumber)
writefile = open(str(SNumber)+'.txt','a')
writefile.write(str(SNumber))
writefile.close()

Upvotes: 1

Related Questions