【问题标题】:os.path.exists() throws error in Windows, not in Pycharm or Ubuntuos.path.exists() 在 Windows 中抛出错误,而不是在 Pycharm 或 Ubuntu 中
【发布时间】:2018-09-02 23:32:40
【问题描述】:

这是我关于 SO 的第一个问题 :D 我目前正在编写一些代码。问题是,以下代码在 Pycharm 和 Ubuntu 中有效……但在 Windows 中无效。

import os, os.path
import configparser
if os.path.exists('config') and os.stat("config/config.ini").st_size>0:
 #do something
else:
 os.makedirs('config')
        password = input("Password: ")
        ip = input("IP Server: ")
        clientname = input("(choosen) Clientname: ")
        config = configparser.ConfigParser()
        config['DEFAULT'] = {'User': user, 'ServerIP': ip, 'Clientname': clientname}
        with open('config/config.ini', 'w+') as configfile:
            config.write(configfile)

Windows 错误[WinError2] 找不到文件 config/config.ini

另一方面,Pycharm 和 Ubuntu 是否做了他们必须做的事情。 有谁知道怎么回事?

【问题讨论】:

  • 某处可能有一个空的config 目录(当前目录因运行方式而异)。使用os.path.getsize() 避免调用stat。您的程序可能在第二部分崩溃,导致config 目录为空。
  • 脚本文件夹为空。但是您的解决方案有效。非常感谢!
  • 您为什么将 Windows 和 Ubuntu 与 PyCharm 进行比较?前者是操作系统,PyCharm 是 Python IDE。是否使用 PyCharm 没有任何区别。
  • @abccd 它在 Pycharm 控制台中工作。但它在 Windows 上的 python shell 中不起作用。但它可以在 ubuntu 上的 python shell 中运行

标签: python python-3.x operating-system pycharm


【解决方案1】:

您的问题是您运行代码的方式之间存在当前目录差异(代码取决于当前目录,这并不是一件好事,要么使用 os.path.dirname(__file__) 使其依赖于脚本位置,要么来自用户目录(os.path.expanduser("~"),适用于 Windows 和 Linux)

这表明您的代码对于config 可以为空这一事实并不可靠,例如,如果第二部分在创建.ini 文件之前崩溃

为了更可靠地检查文件是否存在且不为空(不是最佳的,2 stat 调用,但是...),您必须在第二部分添加额外的检查以创建目录如果不存在'不存在。

我愿意:

  config_file = "config/config.ini"
  if os.path.exists(config_file) and os.path.getsize(config_file):
     # do something
  else:
    config_dir = os.path.dirname(config_file)
    if not os.path.isdir(config_dir):
        os.makedirs('config')
    # now do the rest to create .ini file, the dir exists

也避免使用'w+'模式,你只想新建一个文件,使用'w'

【讨论】:

  • 权限错误[Errno 13] 权限被拒绝“config/config.ini”
  • 以管理员身份启动cmd
  • 不要。使用我在回答开头提到的绝对路径。
  • 好的。我将我的代码编辑为您的答案。但我发现了一些奇怪的行为。 script.py->open with: python ->Error Code, can't open something or something isnt there 但是当我将.py文件的默认程序从Pycharm更改为Python时......它可以工作。
猜你喜欢
  • 2015-02-24
  • 2020-03-02
  • 2021-10-18
  • 1970-01-01
  • 1970-01-01
  • 2016-02-24
  • 2017-08-06
  • 1970-01-01
  • 1970-01-01
相关资源
最近更新 更多