【问题标题】:How to put multiple user inputs in a text file?如何将多个用户输入放入一个文本文件中?
【发布时间】:2022-11-21 23:47:00
【问题描述】:

这是我现在的代码

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()

预期的输出

>> 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!

我尝试了上面的代码,只得到了文本文件中的最后一个用户输入。我应该从 def main() 传递文件名,但我不知道该怎么做,我一直收到无法访问的错误。有人可以帮助我并解释我做错了什么吗?感谢您的时间和考虑。

【问题讨论】:

  • 您需要 append 方法,而不是 write。您每次都在覆盖文件。
  • 阅读documentation of open()。模式'w' 表示打开写入,首先截断文件,这意味着它清除了文件的所有内容。

标签: python python-3.x


【解决方案1】:

请注意

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

您正在使用 w 模式,每次都会覆盖文件。相反,使用 a+ 模式,它附加到文件,如果文件尚不存在则创建文件。

【讨论】:

    【解决方案2】:

    您正在使用 write (w) 文件方法,它会用您传递的任何新数据覆盖您的文件。您需要 append (a) file 方法,它每次都会附加到您的文件中。

    The BSD fopen manpage定义文件方法如下:

    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.
    

    【讨论】:

    猜你喜欢
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多