开发者

Read/Write text files in Python

开发者 https://www.devze.com 2023-04-11 09:22 出处:网络
I\'m fairly new to Python and don\'t fully understand all items and I\'ve been given a base for a programme and I need to alter bits, here\'s what I have so far:

I'm fairly new to Python and don't fully understand all items and I've been given a base for a programme and I need to alter bits, here's what I have so far:

    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

I am completely lost as to why it doesn't currently work as it's finding a Syntax error with: for name, value in bearing.iteritems():

I'm not sure whether some mistakes are due to indentation..

I also don't quite understand the last part. I have an output text file and this is what the final part is reading. I have however don't understand (in particular) this line:

regexp = re.compile( "^(?P<name>.*)\\s*=\\s*(?P<va开发者_Python百科lue>.*)$" )

With the RE's, I don't understand exactly what it means by 'matching' what is the ^, $ and ?P matching to what? Also what does 'regexp' represent?

Thank you for your time =)


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

Has 2 left ( and only 1 right ). This appears to be a syntax error.

Since the statement isn't complete, Python continues parsing. The error message shows up on the following line.


Read this: http://docs.python.org/library/re.html#regular-expression-syntax. Then update your question with more specific aspects of the regular expression which confuse you. Regular expressions are a (potentially) deep topic.

0

精彩评论

暂无评论...
验证码 换一张
取 消