简体   繁体   English

如何将多个用户输入放入一个文本文件中?

[英]How to put multiple user inputs in a text file?

this is the code I have right now这是我现在的代码

fname = input(">>Please Enter a file name followed by .txt ")
def writedata():
    i=0
for i in range(3):
    f = open(f"{fname}", 'w')
    stdname = input('>>\tStudent Name: \t')
    marks = input('>>\tMark for exam: \t')
    f.write(stdname)
    f.write("\n")
    f.write(marks)
f.close()

def main():
    writedata()

the output that is intended预期的 output

>> Please Enter a file name, followed by .txt: studentRecord.txt
>> Enter record for student 1 in the format of [1. Name, 2. Mark]:
>>       Student Name: James White
>>       Mark for exam: 100
>> Enter record for student 2 in the format of [1. Name, 2. Mark]:
>>       Student Name: James Brown
>>       Mark for exam: 85
>> Enter record for student 3 in the format of [1. Name, 2. Mark]:
>>       Student Name: James King
>>       Mark for exam: 75
>> Student record writing completed!

I tried the above code and only got the last user input in the text file.我尝试了上面的代码,只得到了文本文件中的最后一个用户输入。 I was supposed to pass file name from def main() but I don't know how to do that, I kept getting unreachable error.我应该从 def main() 传递文件名,但我不知道该怎么做,我一直收到无法访问的错误。 Can someone please help me and explain what I'm doing wrong?有人可以帮助我并解释我做错了什么吗? Thank you for your time and consideration.感谢您的时间和考虑。

Please take note of请注意

    f = open(f"{fname}", 'w')

You are using the w mode, which overwrites the file everytime.您正在使用w模式,每次都会覆盖文件。 Instead, use a+ mode, which appends to the file, and creates the file if it does not yet exist.相反,使用a+模式,它附加到文件,并在文件尚不存在时创建该文件。

  fname = str(input(">> Please Enter a file name, followed by .txt: "))
  f = open(f"{fname}","a+")
  for i in range(1, 4):
      print(f">> Enter record for student {i} in the format of [1. Name, 2. Mark]:")
      stdname = str(input(">>      Student Name: "))
      marks = str(input(">>      Mark for exam: "))
      f.write(stdname)
      f.write("\n")
      f.write(marks)
      f.write("\n")
  print("Student record writing completed!")
  f.close()
def main():
  writedata()
if __name__ == '__main__':
  main()

Thank you guys for your help.谢谢你们的帮助。 This is the answer I came up with.这是我想出的答案。

You are using the write (w) file method, which overwrites your file with any new data you pass.您正在使用write (w)文件方法,它会用您传递的任何新数据覆盖您的文件。 You need the append (a) file method, which will append to your file each time.您需要append (a)文件方法,每次都会将 append 写入您的文件。

The BSD fopen manpage defines the file methods as follows: BSD fopen 联机帮助页定义文件方法如下:

The argument mode points to a string beginning with one of the following
 sequences (Additional characters may follow these sequences.):

 ``r''   Open text file for reading.  The stream is positioned at the
         beginning of the file.

 ``r+''  Open for reading and writing.  The stream is positioned at the
         beginning of the file.

 ``w''   Truncate file to zero length or create text file for writing.
         The stream is positioned at the beginning of the file.

 ``w+''  Open for reading and writing.  The file is created if it does not
         exist, otherwise it is truncated.  The stream is positioned at
         the beginning of the file.

 ``a''   Open for writing.  The file is created if it does not exist.  The
         stream is positioned at the end of the file.  Subsequent writes
         to the file will always end up at the then current end of file,
         irrespective of any intervening fseek(3) or similar.

 ``a+''  Open for reading and writing.  The file is created if it does not
         exist.  The stream is positioned at the end of the file.  Subse-
         quent writes to the file will always end up at the then current
         end of file, irrespective of any intervening fseek(3) or similar.

You could also look at python's documentation for some more information: https://docs.python.org/3/library/functions.html#open您还可以查看 python 的文档以获取更多信息: https://docs.python.org/3/library/functions.html#open

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM