Rossive
Rossive

Reputation: 33

Creating files in python

name = input("What is your name")
myFile = open(name, 'score.txt', 'wt')
myFile.write('score: 6')
myFile.close()

As you can see this program creates a ".txt" file where it is saved, what I want to know is if I can name the file a name, for example Sam inputs his name I want the file to save itself as "Sam score.txt" with the score 6 inside it, is this possible. Thanks. - P.S kinda new so don't really know if this is correct thanks.

Upvotes: 0

Views: 73

Answers (2)

Wilco van Esch
Wilco van Esch

Reputation: 457

Simply add the + operator to concatenate the variable and string.

name = raw_input("What is your name?")
myFile = open(name + ' score.txt', 'w')
myFile.write('Score: 6')
myFile.close()

You'll notice I've added a space in ' score.txt' to ensure it becomes 'Sam score' rather than 'Samscore'.

Upvotes: 1

Vishnu Upadhyay
Vishnu Upadhyay

Reputation: 5061

Do this:-

name = raw_input("What is your name")
myFile = open(name+'score.txt', 'wt') #Concatenate the string.
myFile.write('score: 6')
myFile.close()

Or use with statement

name = raw_input("What is your name")
with open(name+'score.txt', 'wt') as f:
    f.write('score: 6')

You don't need to specifically close it.

Upvotes: 0

Related Questions