使用Python打印文件中的新行

2024-09-28 22:31:52 发布

您现在位置:Python中文网/ 问答频道 /正文

我使用了以下代码。genetarated_rtl.v文件包含带\n字符的文本。它没有新线。但新行字符是打印出来的。你知道吗

  #!/usr/bin/python
    filePath = '/delsoft/lakmald2/Auto/2-GEN/1-Test/for_simple1.rgt'

    rtl = open ('generated_rtl.v', 'wb')
    f = open(filePath,'r')

    def insertSTR(conData):
        printToFile(conData)
        sys.stdout.write(conData)

    def printToFile(data):
        rtl.write(data)

    def insertUSR(conData):
        currentInput = input (conData)
        printToFile(str(currentInput))  

    for line in f:
        conTyp,conData = line.split("::")
        #print conTyp+" is "+conData

        if conTyp == 'STR':
            insertSTR(conData)
        elif conTyp == 'USR':
            insertUSR(conData);

        else :
            print 'ERROR'       

    rtl.close()

当我给出下面的for\u simple1.rgt文件时,\n会被打印出来。我不想那样。我想要的是一条新线路。你知道吗

STR::for (int i=0;i<
USR::
STR::;i++)\nbegin\n
CON::
STR::end\n
END::

Tags: 文件fordefopen字符writertlstr
2条回答

要将后跟文字“n”的文字反斜杠转换为换行符,可以使用string_escape编码对字符串进行解码:

>>> s = r'what\nwhat\nwhat'
>>> print(s)
what\nwhat\nwhat
>>> print(s.decode('string_escape'))
what
what
what
>>>

所以你的功能是:

def printToFile(data):
    rtl.write(data.decode('string_escape'))

您可以尝试^{}函数:

def printToFile(data):
    new_data = data.replace('\\n', '\n')
    rtl.write(new_data)

相关问题 更多 >