简体   繁体   English

Python open("file", "w+") 不创建不存在的文件

[英]Python open("file", "w+") not creating a nonexistent file

Similar questions exist on Stack Overflow. Stack Overflow 上也存在类似的问题。 I have read such questions and they have not resolved my problem.我已经阅读了这些问题,但它们并没有解决我的问题。 The simple code below results in a File Not Found Error.下面的简单代码导致文件未找到错误。 I am running Python 3.9.1 on Mac OS X 11.4我在 Mac OS X 11.4 上运行 Python 3.9.1

Can anyone suggest next steps for troubleshooting the cause of this?任何人都可以建议下一步解决此问题的原因吗?

with open("/Users/root/test/test.txt", "w+") as f:
    f.write("test")
Traceback (most recent call last):
  File "/Users/root1/PycharmProjects/web_crawler/test.py", line 1, in <module>
    with open("/Users/root/test/test.txt", "w+") as f:
FileNotFoundError: [Errno 2] No such file or directory: '/Users/root/test/test.txt'

**sometimes the compiler can't find any path like that you insert in open() function. **有时编译器找不到您在 open() 函数中插入的任何路径。 at that time as possible you can save by default in the folder where your programs were saved by IDE.那时你可以默认保存在IDE保存程序的文件夹中。 the followed syntax may be helpful for you **以下语法可能对您有所帮助**

with open('test.txt', 'w+') as f:
     f.write("xyz")

**here the text.txt will save default in the folder where your IDE stores the program that you write. **这里的 text.txt 将默认保存在您的 IDE 存储您编写的程序的文件夹中。 you can check that folder for conformation **您可以检查该文件夹的构造**

You comments on initial post clarify what you need to happen.您对初始帖子的评论阐明了您需要发生的事情。
Below assumes that下面假设

  • The directory Users/root1/ exists目录Users/root1/存在
  • You are trying to create a new sub directory + file inside it您正在尝试在其中创建一个新的子目录 + 文件
import os

# Wrap this in a loop if you need
new_dir = 'test' # The variable directory name
new_path = 'Users/root1/' + new_dir + "/"
os.makedirs(os.path.dirname(new_path), exist_ok=True) # Create new dir 'Users/root1/${new_dir}/

with open(new_path + "test.txt", "w+") as f:
    # Create new file in afore created directory
    f.write("test")

This creates a new directory based on a variable new_dir and creates the file test.txt in it.这将基于变量new_dir创建一个新目录,并在其中创建文件test.txt

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

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