【发布时间】:2018-03-23 07:15:54
【问题描述】:
我有一个名为 list.txt 的文件,如下所示:
input1
input2
input3
我确定最后一行 (input3) 之后没有空行。然后我有一个 python 脚本,它将逐行读取该文件并将文本写入更多文本以创建 3 个文件(每行一个):
import os
os.chdir("/Users/user/Desktop/Folder")
with open('list.txt','r') as f:
lines = f.read().split('\n')
#for l in lines:
header = "#!/bin/bash \n#BSUB -J %s.sh \n#BSUB -o /scratch/DBC/user/%s.sh.out \n#BSUB -e /scratch/DBC/user/%s.sh.err \n#BSUB -n 1 \n#BSUB -q normal \n#BSUB -P DBCDOBZAK \n#BSUB -W 168:00\n"%(l,l,l)
script = "cd /scratch/DBC/user\n"
script2 = 'grep "input" %s > result.%s.txt\n'%(l,l)
all= "\n".join([header,script,script2])
with open('script_{}.sh'.format(l), 'w') as output:
output.write(all)
我的问题是,这会创建 4 个文件,而不是 3 个:script_input1.sh、script_input.sh、script_input3.sh 和 script_.sh。最后一个文件没有文本,其他文件将有 input1 或 input2 或 input3。
似乎 Python 会逐行读取我的 list.txt,但是当它到达“input3”时,它会以某种方式继续吗?如何告诉 Python 逐行读取我的文件,以“\n”分隔,但在最后一个文本之后停止?
【问题讨论】:
-
我会这样说again:你可能应该重新考虑你的方法。
标签: python bash for-loop newline