我将如何用python写入文件

时间:2015-12-10 14:33:50

标签: python file

如何将分数写入文件?

url(r'^(?P<slug>[\w|\-]+)/$', views.post, name='post'),
url(r'^vote/post/$', views.vote_for_post, name='vote_for_post'),
url(r'^add/post/$', PostCreateView.as_view(), name='post-add'),
url(r'^add/category/$', views.add_category, name='add_category'),

3 个答案:

答案 0 :(得分:1)

这是您打开和写入文件的方式:

# Open a file
fo = open("foo.txt", "w") # Creates a file object 'fo'
fo.write("Output text goes here")

# Close opened file (good practice)
fo.close()

答案 1 :(得分:0)

您可以手动打开和关闭文件,但最好使用Python 3.4.3 (v3.4.3:9b73f1c3e601, Feb 23 2015, 02:52:03) [GCC 4.2.1 (Apple Inc. build 5666) (dot 3)] on darwin Type "help", "copyright", "credits" or "license" for more information. >>> test_dict = {1:"one",2:"two"} >>> set3=set(test_dict) >>> print(set3) {1, 2} >>> set3.add(3) >>> print(set3) {1, 2, 3} >>> set3.pop() 1 >>> print(set3) {2, 3} ,因为它会处理为您关闭文件。

with

with open("score_file.txt",'a') as f: f.write(score) 表示附加到文件,该文件不会覆盖您可能正在查找的先前内容。据我所知,你想要在print语句之后或之前添加它。如果您不理解读取和写入文件,那么您应该查看this

答案 2 :(得分:0)

以下是打开和写入文件的代码示例。

import random

score = 0
question = 0
output = open('my_score', 'a')
for i in range(10):
   num1 = random.randint(1, 10)
   num2 = random.randint(1, 10)
   ops = ['+', '-', '*']
   operation = random.choice(ops)
   Q = int(input(str(num1) + operation + str(num2)))

   if operation == '+':
       answer = num1 + num2
       if Q == answer:
           print("correct")
           score += 1

       else:
           print('You Fail')

   elif operation == '-':
       answer = num1 - num2
       if Q == answer:
           print("correct")
           score += 1
       else:
           print("you fail")
   else:
       answer = num1 * num2
       if Q == answer:
           print("correct")
           score += 1
       else:
           print("you fail")

print("thank you for playing your score is", score)
output.write(score)
output.close()