Python 逐行输出文本&去掉换行符

重点:

readline()或者其它读方法都是带换行符号的,如果不加处理直接调用,会出现无法识别的路径等问题。

所以每行命令作为cmd 调用,一定要去掉“\n”,方法就是strip("\n"),两种途径实现。

方法1:从文件读出,每行输出

写进文件SYNC_LIST。txt

'''//sw/gpgpu/build/...
//sw/gpgp/opencl/apps/...
//sw/gpgp/cuda/import
//sw/gpgp/cuda/common/...
//sw/tools/sdk/WinSDK/8.1/...

'''

LIST = open("SYNC_LIST.txt")
try:
    for line in LIST:
        print line.strip('\n'))
        
finally:
    LIST.close()

或:
with open("SYNC_LIST.txt") as file:
     for line in file:
        print line.strip("\n")

 

 

方法2:用(长)字符串处理

 1 SYNC_LIST ='''//sw/gpgpu/build/...
 2 //sw/gpgp/opencl/apps/...
 3 //sw/gpgp/cuda/import
 4 //sw/gpgp/cuda/common/...
 5 //sw/tools/sdk/WinSDK/8.1/...
 6 '''
 7 
 8 LIST = SYNC_LIST.splitlines(True)
 9     for line in LIST:
10         print line.strip('\n')

 

posted @ 2019-10-25 10:53  浪淘砂  阅读(3074)  评论(0编辑  收藏  举报