【问题标题】:open("text.txt","w+") does not create a new fileopen("text.txt","w+") 不创建新文件
【发布时间】:2023-03-08 01:54:01
【问题描述】:

我正在尝试使用 open(filename,'x') 创建一个文本文件。我试过 x = 'a+'、'w+'、'w'。我正在使用 Windows 10、vs 代码“在终端中运行 python 文件”和 python 3.8.2

    import os

    print("cwd",os.getcwd())

    scriptpath = os.path.dirname(__file__)

    filename = "test.txt" #1
    #filename = scriptpath + "/test.txt" #2
    #filename = r"C:\Users\harki\Documents\ALGO\ALGO-NPL\test.txt" #3

    f = open(filename,'w+')
    f.write("test")
    f.close()

以第一个文件名运行:

PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
  File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
    f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'test.txt'

使用第二个文件名运行:

PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
  File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
    f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'c:/Users/harki/Documents/ALGO/ALGO-NPL/test.txt'

使用第三个文件名运行:

PS C:\Users\harki\Documents\ALGO\ALGO-NPL> & C:/Users/harki/AppData/Local/Programs/Python/Python38/python.exe c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py
cwd C:\Users\harki\Documents\ALGO\ALGO-NPL
Traceback (most recent call last):
  File "c:/Users/harki/Documents/ALGO/ALGO-NPL/test_save.py", line 11, in <module>
    f = open(filename,'w+')
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\harki\\Documents\\ALGO\\ALGO-NPL\\test.txt'

编辑: 将项目移到“文档”文件夹之外解决了问题

【问题讨论】:

  • 与问题无关,我只是好奇:我总是看到这里的人使用w+ 而不是w,即使他们只是在写作,而不是在阅读。你为什么这样做?
  • 我运行了你的代码,对我来说效果很好。检查简单的错误,例如意外运行不同版本的 Python 或 VSCode 问题。我在使用 VSCode 开发 Python 3.x.x 和 C++ 时遇到了一些问题。
  • 我无法复制问题。您的代码工作正常。也许这是一个权限问题?您是否尝试在管理员模式“以管理员身份运行”下运行 cmd/powershell?

标签: python file-io filenotfoundexception file-not-found


【解决方案1】:

我使用这段代码来定义文件路径,它对我有用:

filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'folder/name', 'test.txt')

然后我使用 joblib 或 pickle 创建文件。

在你的情况下,它类似于第二个文件名,只需要添加join()函数

【讨论】:

  • 不应该是os.path.join()吗?
  • 是的,我使用 from os.path import join, dirname, realpath 导入它。所以应该是 os.path.join(dirname(realpath(file)), 'folder/name', 'test.txt')
  • 您应该在答案中明确说明。
  • 完成,我改了。
  • filename = os.path.join(os.path.dirname(os.path.realpath(__file__)), 'test.txt') 创建与上述文件名 #3 相同的路径和错误
猜你喜欢
  • 2021-12-26
  • 1970-01-01
  • 2021-06-05
  • 2021-07-22
  • 1970-01-01
  • 1970-01-01
  • 2013-08-09
  • 2011-02-27
  • 1970-01-01
相关资源
最近更新 更多