【问题标题】:Write input to file, excluding final line将输入写入文件,不包括最后一行
【发布时间】:2018-10-06 15:07:15
【问题描述】:

我的简单任务是编写一个请求文件名的函数,然后反复从用户那里读取行并将这些行保存到命名文件中。

当用户输入本身是一行上的一个点时,它会停止保存行。不保存包含单个点的行。

示例输出如下所示:

Save to what file: mytest.txt
> This is
> my attempt at
> the problem.
>
> The last line was empty
> .
Saving file mytest.txt
5 lines saved

这是我的尝试:

def savefile():
    filename = input("Save to what file: ")
    infile = open(filename, "w")
    line = ""
    lineCount = 0
    while line != ".":
        line = input("> ")
        infile.write(line + "\n")
        lineCount += 1


    print("Saving file", filename)
    print(lineCount, "lines saved")

    infile.close()

效果很好,除了我的while 循环还保存了最后一行(“。”本身在一行上)。我也试过if-else循环:

if line != ".":
    line = input("> ")
    infile.write(line + "\n")
    lineCount += 1
else:
    infile.close()

但这只是保存输入的第一行。

如何排除输入的最后一行?

【问题讨论】:

    标签: python-3.x file for-loop while-loop


    【解决方案1】:

    只是有点乱,经典问题,把输入移到while循环上面,希望看看为什么...

    def savefile():
        filename = input("Save to what file: ")
        infile = open(filename, "w")
        line = ""
        lineCount = 0
        # first lets get the line of input
        line = input("> ")
        # if the line is "." then don't do the following code.
        while line != ".":
            # if the line was not "." then we do this...
            infile.write(line + "\n")
            lineCount += 1
            # get the input again, and loop, remember if we get "."
            # we will break from this loop.
            line = input("> ")
    
    
        print("Saving file", filename)
        print(lineCount, "lines saved")
    
        infile.close()
    

    【讨论】:

    • 我明白为什么line = input"> " 必须在循环之前,但是当我这样做时,函数进入看起来像无限循环的状态,永远不会进入“保存文件”阶段。这是为什么呢?
    • 我在代码中添加了 cmets,希望有助于理清思路。
    【解决方案2】:

    您可以通过简单地交换代码中的一些行来尝试此操作,如下所示:

    def savefile():
        filename = input("Save to what file: ")
        infile = open(filename, "w")
        line = input("> ")
        lineCount = 0
        while line != ".":
            infile.write(line + "\n")
            lineCount += 1
            line = input("> ")
    
    
        print("Saving file", filename)
        print(lineCount, "lines saved")
    
        infile.close()
    

    【讨论】:

      【解决方案3】:

      甚至不需要解释:

      with open("my_file.txt","w") as file:
          while True:
              line = input("> ")
              if line.strip() == ".":
                  break
              else:
                  file.write(line + "\n")
      

      【讨论】:

        猜你喜欢
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 1970-01-01
        • 2011-08-26
        • 1970-01-01
        • 2021-11-22
        相关资源
        最近更新 更多