You need to enable JavaScript to run this app.
优惠活动
大模型
产品
解决方案
定价
更多

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 like test.txtw. The open() function expects the filename and mode as separate arguments.
  • Wrong equality check: In Python, = is for assignment, not comparison. Use == to check if mode equals "w".
  • Calling write() on the wrong object: You tried to call write() on the fileName string variable, but only the file object returned by open() 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()

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.txt on Windows or /home/user/test.txt on Linux/macOS).

内容的提问来源于stack exchange,提问作者Will

相关产品推荐
方舟 Agent Plan

超全模态模型 × Harness 升级,最新支持 Deepseek-V4.1-Flash、GLM-5.3 系列、Doubao-Seedream-5.0-pro、Kimi-K3 (部分), 限时 9.9 元起

最近更新时间:2026.05.21 08:40:46