Python 3.5.2中write函数使用及精准查找文件问题求助
Fixing Your Python File Write Code (Python 3.5.2)
Let's break down the issues in your code and fix them step by step:
Key Issues in Your Current Code
- Incorrect
open()parameters: You're concatenating the mode string (w) to the filename, which creates invalid filenames liketest.txtw. Theopen()function expects the filename and mode as separate arguments. - Wrong equality check: In Python,
=is for assignment, not comparison. Use==to check ifmodeequals"w". - Calling
write()on the wrong object: You tried to callwrite()on thefileNamestring variable, but only the file object returned byopen()has this method. - Unnecessary semicolons: Python doesn't require semicolons at the end of lines (they're allowed but not standard practice).
Corrected Basic Version
This fixes the core issues and ensures you target the right file:
fileName = input("What file do you want to target?(add file type i.e. .exe,.html,.txt)") print("Opening the file...") mode = input("w,r,r+ or a?") if mode == "w": # Pass filename and mode as separate arguments to open() writeToFile = open(fileName, mode) # Use the file object to call write() writeToFile.write("sample text") # Always close the file when done to free resources writeToFile.close()
Recommended Version (Using with Statement)
For better resource management, use Python's with statement—it automatically closes the file when you're done, even if an error occurs:
fileName = input("What file do you want to target?(add file type i.e. .exe,.html,.txt)") print("Opening the file...") mode = input("w,r,r+ or a?") if mode == "w": # The with block handles file closing automatically with open(fileName, mode) as writeToFile: writeToFile.write("sample text")
Quick Notes for Python 3.5.2
- The
"w"mode will create the file if it doesn't exist, or overwrite its contents if it does. Use"a"if you want to append to an existing file instead. - Always make sure the file path is correct—if the file isn't in your script's working directory, you'll need to provide the full path (e.g.,
C:/Documents/test.txton Windows or/home/user/test.txton Linux/macOS).
内容的提问来源于stack exchange,提问作者Will
相关产品推荐
相关产品推荐

