Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Welcome To Ask or Share your Answers For Others

Categories

0 votes
4.6k views
in Technique[技术] by (71.8m points)

python - How can I create a path for file.write to follow when opening a file in append

am trying to use file.write() to write the results of a score-calculating program into a file named Score.txt but when it is run the file is left blank, How can I find where a text file is being created or specify the path it should take to write the text file?

The file is stored in the same folder as the text file I am trying to edit f= open("Score.txt", "a")

country = input('what country?
')
gold = int(input('how many gold medals does the country have?
'))
gold=gold*3
silver =int(input('how many silver medals does the country have?
'))
silver=silver*2
bronze = int(input('how many bronze medals does the country have?
'))
total = gold + silver + bronze
total = str(total)
print(country, 'got', total)
f.write('
')
f.write(country)
f.write('
')
f.write('
 = 
')
f.write('
')
f.write(total)
f.write('
')
f.write('test')
f.close()

与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome To Ask or Share your Answers For Others

1 Answer

0 votes
by (71.8m points)

The text file should be created in the same directory that you are running your python script.

This is because you haven't changed the path of your f= open("Score.txt", "a")

You can also declare a relative path or absolute path to your Score.txt file.

Absolute path open Score.txt from an absolute location

f = open(r"C:my_programsScore.txt","a")

Relative Path open myFile from the parent directory of current python script.

f = open("../Score.txt","a")


与恶龙缠斗过久,自身亦成为恶龙;凝视深渊过久,深渊将回以凝视…
Welcome to OStack Knowledge Sharing Community for programmer and developer-Open, Learning and Share
Click Here to Ask a Question

...