You need to enable JavaScript to run this app.
最新活动
大模型
产品
解决方案
定价
生态与合作
支持与服务
开发者
了解我们

如何在Windows7的Anaconda环境下用Python3的Jupyter Notebook6.0.3创建testfile.txt及解决文件找不到错误

Hey there, let's work through this FileNotFoundError you're facing in your Jupyter Notebook setup (Windows 7, Anaconda Python 3, Notebook 6.0.3)! Let's break down what's happening and fix it step by step.

First, spot the obvious typo in your error message

Take a close look at the error you got:

FileNotFoundError: [Errno 2] No such file or directory: 'test file.txt'

Notice the space in test file.txt? But your code uses testfile.txt (no space). That's likely a simple typo first off—make sure the filename in your code matches exactly what you intend to create/access.

The core issue: Wrong file open mode

You mentioned you want to create testfile.txt, but your code uses the "r" (read-only) mode. This mode requires the file to already exist—if it doesn't, Python throws the FileNotFoundError you're seeing. Here's how to fix this based on what you need:

1. Create the file and write content (most common use case)

Use the "w" (write) mode—it will automatically create the file if it doesn't exist. For best practice, use a context manager (it handles closing the file for you, so you don't forget):

# Create testfile.txt and write some content
with open("testfile.txt", "w") as file1:
    file1.write("This is my test file content!")

If you prefer the traditional open()/close() approach (just remember to close the file):

file1 = open("testfile.txt", "w")
file1.write("This is my test file content!")
file1.close()

2. Only create an empty file (no content)

If you just need an empty file and want to avoid accidentally overwriting an existing one, use the "x" (exclusive creation) mode—it will throw an error if the file already exists, which is a safe guard:

try:
    with open("testfile.txt", "x") as file1:
        print("Empty testfile.txt created successfully!")
except FileExistsError:
    print("Oops, testfile.txt already exists!")

3. Verify your Jupyter working directory

If you've fixed the filename and mode but still get the error, check where Jupyter is looking for files. Run this code to see your current working directory:

import os
print(os.getcwd())

If your intended file isn't in this directory, either move the file to this path, or use the full absolute path in your open() call (for Windows, use double backslashes or a raw string):

# Example absolute path on Windows
with open(r"C:\Users\YourName\Documents\testfile.txt", "w") as file1:
    file1.write("Content using absolute path")
Once the file exists, you can use read mode

After creating the file with one of the above methods, your original code file1 = open("testfile.txt", "r") will work just fine (again, make sure the filename matches exactly!).

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

火山引擎 最新活动