0

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.

1

2 Answers 2

1
import random
SNumber=random.randint(199999,999999)
print(SNumber)
writefile = open(str(SNumber)+'.txt','a')
writefile.write(str(SNumber))
writefile.close()
Sign up to request clarification or add additional context in comments.

Comments

0
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()

5 Comments

Hi sir, what if i will open the said file for file checker. umm because if the data already exists in the file. it will be discarded.
I'm not so familiar with Python. And so, not understand your comment.
If you have used open(name, 'a') then it will not be discarded. open(name, 'w') will discard earlier data's in file
Does it helped?
yes sir. it helped. just my 2nd code does not jam with your code. and it is my only problem sir. Thank You

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.