Speak now
Please Wait Image Converting Into Text...
Embark on a journey of knowledge! Take the quiz and earn valuable credits.
Challenge yourself and boost your learning! Start the quiz now to earn credits.
Unlock your potential! Begin the quiz, answer questions, and accumulate credits along the way.
General Tech Learning Aids/Tools 2 years ago
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.
Turn Your Knowledge into Earnings.
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()
The problem is here:
oldFile = open(f"{f}", "r")
The open function needs a filename, a string like "test.txt".
open
"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.
f
f"{f}"
"<_io.TextIOWrapper name='test.txt' mode='w+' encoding='cp1252'>"
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.
newFile
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.
return
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.
write
close
flush
So, you want to move the f.close() to before the return.
f.close()
Or, even better, use a with statement, which makes sure the file gets closed automatically when you're done with it.
with
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)
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.
General Tech 9 Answers
General Tech 7 Answers
General Tech 3 Answers
General Tech 2 Answers
Ready to take your education and career to the next level? Register today and join our growing community of learners and professionals.