2011-10-06 57 views
0

我對Python相當陌生,並沒有完全理解所有項目,並且我已經給出了一個程序的基礎,並且需要修改位,以下是迄今爲止的內容:在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 

我完全失去了,爲什麼,因爲它是找到一個語法錯誤與它沒有目前的工作:爲名稱,在bearing.iteritems()值:

我不知道是否有些錯誤是由於縮進..

我也不太明白最後一部分。我有一個輸出文本文件,這是最後一部分正在閱讀的內容。我可是有不明白(特別是)這行:

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

隨着RE的,我不明白到底是什麼意思的「匹配」什麼是^,$和P匹配的是什麼? ?另外'regexp'代表什麼?

謝謝您的時間=)

+1

」語法錯誤:for name,value in bearing.iteritems()「?請在您的問題中包含實際的語法錯誤輸出。 –

+1

如果你的代碼是真正的代碼,brg(或軸承)沒有定義之前,你使用它進入循環... –

+0

「我......不明白(特別是)這一行:」和「在非常簡單條款「很難做到。請說明你做了什麼,不明白這條線。我們不知道你的意思是多麼「簡單」。我們不知道你理解哪些部分。請提供一些您認爲可能的摘要,以便我們能夠延長和更正您的陳述。 –

回答

3
 logger.critical("Failed to create file \"%s\" : %s" % (filename, e) 

有2個左(只有1右)。這似乎是一個語法錯誤。

由於語句不完整,Python會繼續解析。該錯誤消息顯示在以下行上。


閱讀原因:http://docs.python.org/library/re.html#regular-expression-syntax。然後更新您的問題與正則表達式的更多具體方面混淆你。正則表達式是一個(可能)很深的話題。 「

+0

BTW,AFAIK'logger.critical'接受格式爲'logger.critical(「創建文件失敗\」%s \「:%s」,文件名,e)''。 – glglgl

+1

謝謝,我不敢相信我沒有看到! – user2063