Python: User inputs filename to write/be written to. program then opens/reads

General Tech Learning Aids/Tools 2 years ago

0 2 0 0 0 tuteeHUB earn credit +10 pts

5 Star Rating 1 Rating

Posted on 16 Aug 2022, this text provides information on Learning Aids/Tools related to General Tech. Please note that while accuracy is prioritized, the data presented might not be entirely correct or up-to-date. This information is offered for general knowledge and informational purposes only, and should not be considered as a substitute for professional advice.

Take Quiz To Earn Credits!

Turn Your Knowledge into Earnings.

tuteehub_quiz

Answers (2)

Post Answer
profilepic.png
manpreet Tuteehub forum best answer Best Answer 2 years ago

 

I am very new to programming and I have tasked myself to write a useless program to aid in learning how to write some function code that didn't come out of a book. The purpose of the program is to write a file with a user inputted filename then add contents to the file. I've made it this far. The problem I am having is from the nd">second half of the program.

The nd">second half is suppose to read you the contents of the file it just made. then ask you if you want to copy the contents to a new file. then assign the new file a user inputted name and copy the contents of the original file.

I am having issues reading the old filename. and also my output from the program looks like this:

Insert 'filename.txt' Here >>> test.txt
user input >>> lolokay
Traceback (most recent call last):
  File "testbed.py", line 45, in <module>
    main()
  File "testbed.py", line 43, in main
    copyToNew(newFile())
  File "testbed.py", line 23, in copyToNew
    oldFile = open(f"{f}", "r")
OSError: [Errno 22] Invalid argument: "<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>"

full code below:

# this program will open a file or make a new file and write to it.
# it will then copy the file contents to a new file.

def newFile():
    # opens user inputted filename ".txt" and (w+) makes new and writes
    f = open(input("Insert 'filename.txt' Here >>> "), 'w+')
    # asks for user input to enter into the file
    usrInput = input("user input >>> ")
    # writes user input to the file and adds new line
    f.write(usrInput)
    f.write("\n")

    # closes the file
    return f
    f.close()

# copy contents and outputs to new file
def copyToNew(f):
    oldFile = open(f"{f}", "r")
    fileContents = oldFile.read()
    print("\n",fileContents)

    # needs to asks user if they would like to copy file to new document
    print(f"Would you like to copy this (name{oldFile})? Y or N")
    usrInput = input("Y or N >>> ")
    print(usrInput)

    if usrInput.lower() in {"y"}:
        print("Your file has been created.")

    elif usrInput.lower() in {"n"}:
        print("Goodbye.")
    else:
        copyToNew(f)

# defines main
def main():
    copyToNew(newFile())

main()
profilepic.png
manpreet 2 years ago

The problem is here:

oldFile = open(f"{f}", "r")

The open function needs a filename, a string like "test.txt".

f is a file object. So, f"{f}" is the string representation of that file object, like "<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>". You're lucky you're on Windows, where that isn't a valid filename; on macOS or Linux, you would have actually created a file with that horrible name and not realized the problem until later.

Anyway, you want to change your newFile function to return the filename, not the file object. Then, the caller will get back something you can open.


While we're at it: once you return from a function, that function is done. Any code you put after the return never runs. Which means you're never closing your file. That's going to cause multiple problems.

For one thing, on Windows, you may not be able to open the same filename while you've still got it open from before.

And, even if you can, you might not see what you write to the file. Because disks are so much slower than CPUs, when you write to a file, it's usually buffered, to be written later when the disk catches up. Unless you close the file (or flush it), the data may not be written yet.

So, you want to move the f.close() to before the return.

Or, even better, use a with statement, which makes sure the file gets closed automatically when you're done with it.


So:

def newFile():
    # asks user for filename
    filename = input("Insert 'filename.txt' Here >>> ")
    # opens user inputted filename ".txt" and (w+) makes new and writes
    with open(filename, 'w+') as f:
        # asks for user input to enter into the file
        usrInput = input("user input >>> ")
        # writes user input to the file and adds new line
        f.write(usrInput)
        f.write("\n")
    return filename

# copy contents and outputs to new file
def copyToNew(f):
    with open(f, "r") as oldFile:
        fileContents = oldFile.read()
    print("\n",fileContents)

    # needs to asks user if they would like to copy file to new document
    print(f"Would you like to copy this (name{oldFile})? Y or N")
    usrInput = input("Y or N >>> ")
    print(usrInput)

    if usrInput.lower() in {"y"}:
        print("Your file has been created.")

    elif usrInput.lower() in {"n"}:
        print("Goodbye.")
    else:
        copyToNew(f)

0 views   0 shares

No matter what stage you're at in your education or career, TuteeHub will help you reach the next level that you're aiming for. Simply,Choose a subject/topic and get started in self-paced practice sessions to improve your knowledge and scores.