简体   繁体   中英

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

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 second half of the program.

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

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)

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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