python - 如何在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等。任何帮助/指导将不胜感激。
解决方案
这是一个小脚本,用于在您运行脚本的目录中输出该文件。
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的有用信息的链接。
推荐阅读
- c# - 何时使用 Task.Run().GetAwaiter().GetResult() 和 ().GetAwaiter.GetResult()?
- pycharm - 在 PyCharm 中,是否可以通过粘贴将文本连接到现有环境变量中?
- kubernetes - 使用 LB 和入口设置 Kubernetes
- android - 错误:javax.net.ssl.SSLHandshakeException - Nativescript
- javascript - 使用套接字 io 将数据传递给 html 表
- r - 关于 Weibull 分布卷积的积分问题
- swift - 对于组合主题类型,“上游订阅”是什么意思?
- r - Easy data tidying hacks for codes like these?
- python - 如何过滤掉对象并仅显示用户在与对象 Django 关联的 ManyToMany 字段中的位置
- apache-spark - SPARK:Spark 中的 CBO 仅适用于 spark-sql 还是也适用于 Dataframe 和 Dataset API?