python - OSError : [Errno 22] Invalid argument on file path while modifying a file

标签 python python-3.x error-handling

我正在用python编写程序来修改XML文件,该程序已经过测试,并且可以在大多数人的计算机上工作,但是我一直有一个用户遇到该标题错误。我无法弄清楚原因,并正在尝试修复

这是我的主要代码。

"""
@author: Taylor May
@date: 04/18/2014
@note: Main Function for CubeBlocks Modifier
"""

import os
import sys
import shutil
import time
import traceback
from xml.dom import minidom

# This is d.py
import logging, logging.handlers

# Make a global logging object.
x = logging.getLogger("logfun")
x.setLevel(logging.DEBUG)

# This handler writes everything to a file.
h1 = logging.FileHandler("myapp.log")
f = logging.Formatter("%(levelname)s %(asctime)s %(funcName)s %(lineno)d %(message)s")
h1.setFormatter(f)
h1.setLevel(logging.DEBUG)
x.addHandler(h1)

# This handler emails me anything that is an error or worse.
h2 = logging.handlers.SMTPHandler('localhost', 'spam@catalysetech.com', ['spam@catalysetech.com'], 'ERROR log')
h2.setLevel(logging.ERROR)
h2.setFormatter(f)
x.addHandler(h2)



try:
    logfun = logging.getLogger("logfun")

    logfun.debug("Inside f!")

    def cls():
        os.system(['clear','cls'][os.name == 'nt'])
        return

    def titleScreen():
        cls()
        os.system("mode con: cols=147 lines=40")
        print('//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////')
        print('/////Author:///////////////   _____      _          ____  _            _          __  __           _ _  __ _           ///////////////////////////')
        print('///////////////////////////  / ____|    | |        |  _ \| |          | |        |  \/  |         | (_)/ _(_)          ///////////////////////////')
        print('/////Catalyse////////////// | |    _   _| |__   ___| |_) | | ___   ___| | _____  | \  / | ___   __| |_| |_ _  ___ _ __ ///////////////////////////')
        print("/////////////////////////// | |   | | | | '_ \ / _ \  _ <| |/ _ \ / __| |/ / __| | |\/| |/ _ \ / _` | |  _| |/ _ \ '__|///////////////////////////")
        print('/////////////////////////// | |___| |_| | |_) |  __/ |_) | | (_) | (__|   <\__ \ | |  | | (_) | (_| | | | | |  __/ |   ///////////////////////////')
        print('////////Ver-0.3b///////////  \_____\__,_|_.__/ \___|____/|_|\___/ \___|_|\_\___/ |_|  |_|\___/ \__,_|_|_| |_|\___|_|   ///////Rev-18Apr14/////////')
        print('//////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////////')
        return

    def dirpath():
        while True:
            print()
            print("Please provide the directory of your steam installation(where Space Engineers is installed)")
            print("Example: 'C:/Program Files (x86)/Steam' for now we need the full directory!")
            dirpath = str(input())
            dirpath = (dirpath+"/SteamApps/common/SpaceEngineers/Content/Data")
            print(dirpath)
            print("Does the path above look correct?")
            print("Make sure it doesn't have extra slashes!")
            response = str(input("Correct? y or n:  "))
            if response == "y" or response == "Y":
                return dirpath

    def ratio():
        print("Now we need to pick the ratio at which you'd like to reduce the times")
        print("You can write the ratio either way, 1/3 = .33 or 3")
        no = float(input("Please type your number here!  "))
        return no

    def ui():
        titleScreen()
        print("This program will run and make a backup of your current file, then modify and replace the original.")
        print("There will be a copy of the original in case something goes wrong or you want to reset your times called Cubeblocks.sbc.bak")
        print()
        print("Lets begin!")
        print()
        pa = dirpath()
        titleScreen()
        print()
        no = ratio()
        titleScreen()
        print()
        filehandler(no,pa)


    def filehandler(ratio,path):
        if ratio < 1:
            ratio = 1/ratio
        print("This program is going to print a whole bunch of statements very quickly now, this is normal and part of testing, it will be removed soon.")
        time.sleep(2)
        xmldoc = minidom.parse(path + "/Cubeblocks.sbc")
        itemlist = xmldoc.getElementsByTagName('BuildTimeSeconds') 
        print(len(itemlist))
        for s in itemlist:
            print(s.childNodes[0].nodeValue, end="")
        print()
        for s in itemlist:
            mod = s.childNodes[0].nodeValue
            mod = int(float(mod))
            mod = mod/ratio
            mod = int(mod)
            mod = str(mod)
            s.childNodes[0].nodeValue = mod
        for s in itemlist:
            print(s.childNodes[0].nodeValue, end="")
        print()

        shutil.copy2(path + "/Cubeblocks.sbc", path + "/Cubeblocks.sbc.bak")
        cuberead = open(path + "/Cubeblocks.sbc.bak", "r")
        cubewrite = open(path + "/Cubeblocks.sbc", "w")

        i=0
        print("Loopstart")
        for line in cuberead:
            if "<BuildTimeSeconds>" in line:
                print("      <BuildTimeSeconds>"+itemlist[i].childNodes[0].nodeValue+"</BuildTimeSeconds>" + '\n', end='', file=cubewrite)
                i = i+1
                print('BuildTimeEdit', end='')
            else:
                print(line, end='', file=cubewrite)
                print("LinePost", end='')
        print()
        cubewrite.close()
        cuberead.close()
        print("Done!")
        time.sleep(2)
        print("GoodBye!")
        time.sleep(1)
    ui()
except:
    logfun.exception("Something awful happened!")
    logfun.debug("Finishing f!")

这是错误:
DEBUG 2014-04-19 23:04:18,841 <module> 39 Inside f!
ERROR 2014-04-19 23:05:02,202 exception 1268 Something awful happened!
Traceback (most recent call last):
  File "D:\workspace\Cubeblocks\src\Main.py", line 137, in <module>
  File "D:\workspace\Cubeblocks\src\Main.py", line 91, in ui
  File "D:\workspace\Cubeblocks\src\Main.py", line 99, in filehandler
  File "C:\Python33\lib\xml\dom\minidom.py", line 1963, in parse
  File "C:\Python33\lib\xml\dom\expatbuilder.py", line 908, in parse
OSError: [Errno 22] Invalid argument: 'E:/Program Files <x86>/Steam/SteamApps/common/SpaceEngineers/Content/Data/Cubeblocks.sbc'
DEBUG 2014-04-19 23:05:04,289 <module> 140 Finishing f!

回溯的文件位置来自我的计算机,Ive使用cx_Freeze编译了此程序,这是其吐出的错误

最佳答案

答案似乎很简单,我应该会发现它更容易。

用户在x86上使用了<>,而不是()

关于python - OSError : [Errno 22] Invalid argument on file path while modifying a file,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/23176207/

相关文章:

python - matplotlib 在 xcode 中用 python 绘图

python - 如何从类访问 Python 模块的私有(private)变量

python - 如何使 pygtk 中的选项卡可关闭?

Python 子包和命名空间

python - 使用正则表达式检测 Twitter 句柄

laravel - Laravel 5处理所有错误

javascript - 如何使用 window.onerror 捕获所有 javascript 错误? (包括道场)

c - C语言中变量声明和错误处理优先级的最佳实践

java - python cgi http响应向内容添加额外的字节

python - 如何在 Python 3.x 中打开给定绝对路径的文件