Home > Net >  Writing in a file and printing the input lines with a row number in python
Writing in a file and printing the input lines with a row number in python

Time:11-08

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. 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
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.
After this, the file yogi.txt shows up in the project folder, with the contents:

1 I know someone you don't know
2 Yogi, Yogi

If opening the output file fails, the following error message should be printed immediately:

Writing the file yogi.txt was not successful.
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..

CodePudding user response:

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. 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:
            count = 0
            while inp := input('>> '):
                count  = 1
                fout.write(f'{count} {inp}\n')
    except IOError:
        print(f"Writing the file {f} was not successful.")

    with open(f, "r") as fin:
        # Strip the newline character
        for line in fin:
            print(line.strip())

if __name__ == "__main__":
    main()
  • Related