首页 > 解决方案 > 如何在python中的文本文件中的每一行增加字符串中的数字?

问题描述

我有我想在 bash 脚本中运行 500 次的代码(尽管目前我一直坚持在 bash 中为我想要的东西制作一个 for 循环,所以我想我可以通过 python 自动制作一个更大的 bash 脚本)。但是,我希望在 500 次迭代中改变其中的一部分 - 我有一个文件 'individual1' 需要随着每一行增加(所以个人 1、个人 2、个人 3 等)

目前在python中我已经简单地完成了:

x  = 'plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual1.txt'

text = ((x+'\n')*500)    

f = open("bash.txt", "r")
out = open("outfile.bg", "w")
for line in f:
    out.write("DBPH" + 1)
out.close()
print(text)
f.close()

虽然我知道这个 for 循环根本不对,但从尝试从这里的类似问题中学习,我仍然不确定接下来要采取哪些步骤来获得我想要的。

文本文件中的输出如下所示:

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual1.txt

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual2.txt

所以我得到了个人1、个人2等。任何帮助/指导将不胜感激。

标签: pythonfor-loop

解决方案


这是一个小脚本,用于在您运行脚本的目录中输出该文件。

x  = 'plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt --recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam '

times_written = 1

out = open("outfile.bg", "w")
while times_written - 1 < 500:
    out.write(F"{x}individual{times_written}.txt\n")
    times_written += 1
out.close()

此块将产生如下输出:

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual1.txt
plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual2.txt

这里的代码将做同样的事情,但中间有一个空格:

x  = 'plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract 
snps.txt --recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam '

times_written = 1

out = open("outfile.bg", "w")
while times_written - 1 < 500:
    out.write(F"{x}individual{times_written}.txt\n\n")
    times_written += 1
out.close()

这将产生如下输出:

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual1.txt

plink --bed chr${ID}.bed --bim chr${ID}.bim --fam chr${ID}.fam --extract snps.txt
--recode vcf-iid --out output${indiv}chr${ID}vcf --keep-fam individual2.txt

快乐编码。这里还有一个关于 Python File I/O https://www.tutorialspoint.com/python3/python_files_io.htm的有用信息的链接。


推荐阅读