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.

Gino Mempin
  • 25,369
  • 29
  • 96
  • 135
  • Does this answer your question? [How do I put a variable inside a string?](https://stackoverflow.com/questions/2960772/how-do-i-put-a-variable-inside-a-string) – Gino Mempin Jan 15 '22 at 02:23

2 Answers2

1
import random
SNumber=random.randint(199999,999999)
print(SNumber)
writefile = open(str(SNumber)+'.txt','a')
writefile.write(str(SNumber))
writefile.close()
Yarn
  • 84
  • 4
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()
Sinto
  • 3,915
  • 11
  • 36
  • 70