简体   繁体   English

在文件中写入并在python中打印带有行号的输入行

[英]Writing in a file and printing the input lines with a row number in python

I have a python program that will ask for user input until an empty line is entered and write them in a file with a line number.我有一个 python 程序,它将要求用户输入,直到输入空行并将它们写入带有行号的文件中。 It will also handle an exception case in case it fails to write in a file.如果它无法写入文件,它还将处理异常情况。 The expected output is:预期的输出是:
Enter the name of the file: yogi.txt输入文件名:yogi.txt
Enter rows of text.输入文本行。 Quit by entering an empty row.通过输入空行退出。
I know someone you don't know我认识一个你不认识的人
Yogi, Yogi瑜珈,瑜珈

File yogi.txt has been written.文件 yogi.txt 已写入。
After this, the file yogi.txt shows up in the project folder, with the contents:之后,文件 yogi.txt 出现在项目文件夹中,内容如下:

1 I know someone you don't know 1 我认识一个你不认识的人
2 Yogi, Yogi 2 瑜伽士,瑜伽士

If opening the output file fails, the following error message should be printed immediately:如果打开输出文件失败,应立即打印以下错误信息:

Writing the file yogi.txt was not successful.写入文件 yogi.txt 不成功。
I wrote the following code:我写了以下代码:

def main():
    f = input("Enter the name of the file: ")
    print("Enter rows of text. Quit by entering an empty row.")
    try:
        file1 = open(f, "w")
        # declaring a list to store the inputs
        list = []
        while (inp := input(" ")):
            list.append(inp)
        for element in list:
            file1.write(element + "\n")

    except IOError:
        print("Writing the file", f, "was not successful.")

    Lines = file1.readlines()
    count = 0
    # Strips the newline character
    for line in Lines:
            count += 1
            file1.write("{} {}".format(count, line.strip()))


if __name__ == "__main__":
    main()

but it shows some error as unsupported operation..但它显示一些错误为不受支持的操作..

The posted code is reading lines from a file that is in write mode so it fails at the Lines = file1.readlines() statement with unsupported operation.发布的代码正在从处于写入模式的文件中读取行,因此它在Lines = file1.readlines()语句处失败,操作不受支持。 Close the file after writing and open it in read mode to echo the contents to the console.写入后关闭文件并以读取模式打开它以将内容回显到控制台。

Also, is there a reason to store input in a list when you can write the lines directly to the file as you enter them.此外,当您可以在输入时将行直接写入文件时,是否有理由将输入存储在列表中。

The following fixes the input and output and removes the temporary list.以下修复输入和输出并删除临时列表。

def main():
    f = input("Enter the name of the file: ")
    print("Enter rows of text. Quit by entering an empty row.")
    try:
        with open(f, "w") as fout:
            while inp := input(" "):
                fout.write(inp + "\n")
    except IOError:
        print("Writing the file", f, "was not successful.")

    with open(f, "r") as fin:
        count = 0
        # Strips the newline character
        for line in fin:
            count += 1
            print("{} {}".format(count, line.strip()))

if __name__ == "__main__":
    main()

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

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