6

I'm trying to write to a file but it's not working. I've gone through step-by-step with the debugger (it goes to the write command but when I open the file it's empty).

My question is either: "How do I see what the error is so I can debug?", "What can go wrong when trying to write to a file that would cause it to behave this way?".

sqlScript = open('script-file.sql', 'a')

    try:
         sqlScript.write(sqlLine)
    except IOError as (errno, strerror):
         print "I/O error({0}): {1}".format(errno, strerror)

This should be simple but I can't seem to find an answer. Also, I apologize in advance as English is a second language.

Edit: I put a print statement just before and the string is not empty.
Edit2: I'm using python 2.6 if that factors in somehow.

Edit 3: I've found a "solution" to my error. I decided to try and run my script using IDLE instead of PyCharm and it works like a charm (pun intended). I have no clue why, but there it is. Any reason why that would happen?!

4

7 回答 7

4

基于克里斯莫里斯的回答,也许做这样的事情:

try:
    sqlScript.write(sqlLine)
except Exception as e:
    print type(e)
    print str(e)

这将捕获任何抛出的异常(Exception当然,前提是它是 的子类)并告诉您类型和错误消息。

此外,可以为不同的可能异常定义多个except:案例,因此可以尝试为每个可能引发/引发的异常执行此操作。

于 2012-04-04T19:36:39.540 回答
2

下面的代码可以让您查看抛出的异常是什么,并查看它的来源。

try:
    sqlScript.write(sqlLine)
except:
    print "Unexpected error:", sys.exc_info()[0]
    raise

有关更多信息,请参阅http://docs.python.org/tutorial/errors.html

于 2012-04-04T19:32:55.823 回答
1

您必须将光标放在文件的开头。你可以用seek方法做到这一点:

myScript.seek(0)

看到这个答案:https ://stackoverflow.com/a/2949648/2119117

于 2014-10-24T10:23:09.813 回答
0

脚本中的关键字是小写的吗?同样的事情在另一个数据库中发生在我身上,我通过将单词更改为大写来解决它。

于 2012-04-04T19:58:41.673 回答
0

您当前的工作目录不是您期望的那样,它正在成功写入script-file.sql另一个目录中的某些目录。尝试打印os.getcwd()并确保它符合您的期望,然后查看该目录。

于 2012-04-04T19:59:43.153 回答
0

如果没有抛出异常,我怀疑字符串变量 'sqlLine' 是空的。

你在写语句之前打印了吗?

于 2012-04-04T19:35:25.870 回答
0

它发生在我的linux环境中,但在windows上工作试试

sqlScript = open('script-file.sql', 'a', buffering=False)

或者

sqlScript = open('script-file.sql', 'a', 0)
于 2016-11-18T21:00:44.283 回答