【问题标题】:Read/Write text files in Python在 Python 中读/写文本文件
【发布时间】:2011-12-02 06:58:36
【问题描述】:

我对 Python 还很陌生,并不完全理解所有项目,我已经获得了一个程序的基础,我需要更改一些位,这是我目前所掌握的:

    import sys, os

    filename   = 'C:\main\in.txt'
    resultFile = 'C:\main\out.txt'

    try:
       file = open( filename, "w" )
    except Exception, e:
        logger.critical( "Failed to create file \"%s\" : %s" % ( filename, e )

    for name, value in brg.iteritems():
        if -1 == string.find( name, "CTRL" ) and name not in [ "name", "type" ]:
            file.write( "%s = %s\n" % ( name, value ) )
            file.close()

   # run the Fortran programme

    resultCode = os.system( '%sC:\main\Debug\main.exe -i %s -o %s.result' % ( options[ OPTION_script_path ], filename, filename ) ) 

    # Read the results

    try:
        file = open( resultFile, "r" ) 
    except Exception, e:
        logger.critical( "Failed to create file \"%s\" : %s" % ( resultFile, e ) 

        regexp = re.compile( "^(?P<name>.*)\\s*=\\s*(?P<value>.*)$" )
        for row in file.xreadlines():
        row = row.strip( "\\r\\n \\t" )
        m = regexp.match( row )
        if m:
                name = m.group( "name" )
                value = m.group( "value" )
                brg[ name ] = value

我完全不知道为什么它目前不起作用,因为它发现了一个语法错误:for name, value in bearing.iteritems():

我不确定某些错误是否是由于缩进造成的..

我也不太明白最后一部分。我有一个输出文本文件,这是最后一部分正在阅读的内容。但是我不明白(特别是)这一行:

regexp = re.compile( "^(?P<name>.*)\\s*=\\s*(?P<value>.*)$" )

对于 RE,我不明白“匹配”是什么意思,^、$ 和 ?P 与什么匹配?还有'regexp'代表什么?

感谢您的宝贵时间 =)

【问题讨论】:

  • “语法错误:对于名称,bearing.iteritems() 中的值”?请在您的问题中包含实际的语法错误输出。
  • 如果你的代码是真正的代码,在你使用它进入循环之前没有定义brg(或bearing)...
  • “我......(特别是)不明白这一行:”和“用非常简单的术语”很难做到。请澄清您对该行的所作所为和不了解的内容。我们不知道您的意思是多么“简单”。我们不知道您了解哪些部分。请提供一些您认为可能的摘要,以便我们扩展和更正您的陈述。
  • 小心:filename = 'C:\main\in.txt' 有效,但 '\n.txt' 无效。因为 \n 是换行符。使用双反斜杠或 r'C:\main\in.txt'
  • @user982297:请停止在您的问题中添加 cmets。请更新您的问题以说明您不理解的内容。在更新您的问题之后,请删除与您对正则表达式的了解(和不了解)相关的两个 cmets。很难从很多 cmets 中综合出一个连贯的问题。如果您更新您的问题会有所帮助。

标签: python file exception


【解决方案1】:
        logger.critical( "Failed to create file \"%s\" : %s" % ( filename, e )

左侧有 2 个 (,右侧只有 1 个 )。这似乎是一个语法错误。

由于语句不完整,Python 继续解析。错误消息显示在以下行。


阅读:http://docs.python.org/library/re.html#regular-expression-syntax。然后更新您的问题,使用正则表达式的更具体方面让您感到困惑。正则表达式是一个(可能)很深的话题。

【讨论】:

  • 顺便说一句,AFAIK logger.critical 也接受logger.critical( "Failed to create file \"%s\" : %s", filename, e) 的形式。
  • 谢谢,我不敢相信我没有看到!
猜你喜欢
  • 2011-08-12
  • 1970-01-01
  • 2013-08-09
  • 2013-06-21
  • 2013-05-12
  • 2018-01-25
  • 2010-09-16
  • 1970-01-01
  • 2012-01-22
相关资源
最近更新 更多