首页 > 解决方案 > 无论如何要重新格式化python脚本?

问题描述

下面我有一个 python 脚本,如果我创建一个.py文件并将以下代码粘贴到其中,它将无法工作

import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991():\r\n    ## a simple code example to test \r\n    for i in range (0 , 10 ):\r\n        print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n    print ("loop reached the end")\r\n    \r\n \r\nif __name__ == "__main__":\r\n    fun_9991()\r\n\r\n\r\n

我的目标是将上面的脚本转换为下面的原始形式,而不必自己编辑

我尝试使用replace()删除\r\n但我没有成功

import os
import time 
import random 
 
def fun_9991():
    ## a simple code example to test 
    for i in range (0 , 10 ):
        print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))
    print ("loop reached the end")
    
 
if __name__ == "__main__":
    fun_9991()

标签: python

解决方案


如果您只是将字符串写入文件,它应该有点工作:

with open('example.py', 'w') as text_file:
    text_file.write("""import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991(): \r\n  # a simple code example to test \r\n    for i in range (0 , 10 ):\r\n        print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n    print ("loop reached the end")\r\n    \r\n \r\nif __name__ == "__main__":\r\n    fun_9991()\r\n\r\n\r\n""")

如果需要,您也可以只执行代码:

exec("""import os\r\nimport time \r\nimport random \r\n \r\ndef fun_9991(): \r\n  # a simple code example to test \r\n    for i in range (0 , 10 ):\r\n        print ( " loop count {} , random number is {} , time is {} ".format(i , random.randrange(10) , int(time.time()/1000)))\r\n    print ("loop reached the end")\r\n    \r\n \r\nif __name__ == "__main__":\r\n    fun_9991()\r\n\r\n\r\n""")

推荐阅读