将输入写入文件,不包括最后一行

时间:2018-04-26 02:53:31

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

我的简单任务是编写一个要求输入文件名的函数,然后重复读取用户的行并将这些行保存到指定的文件中。

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

示例输出如下:

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

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

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

3 个答案:

答案 0 :(得分:1)

甚至不需要解释:

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

答案 1 :(得分:1)

您可以通过简单地在代码中交换一些行来尝试这一点,如下所示:

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

答案 2 :(得分: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()