替换文本并保存在新文件中文本Python

2024-10-05 14:28:47 发布

您现在位置:Python中文网/ 问答频道 /正文

它们是Python的第一个武器,我需要创建一个简单的脚本,将所有文本文件放入输入(一个可选择的文件夹)。你知道吗

对于每个文本文件,删除行“#Constructed from biom file”,并将“#OTU ID”替换为“OTU ID”。你知道吗

然后将其保存到另一个文本文件中,该文件保留文件名的第一部分,然后添加“_mod.txt文件“到文件名的末尾。你知道吗

脚本必须为目录中的所有文件自动执行所有这些操作。你知道吗

#!/usr/bin/python
#
import os,sys,uuid
#

with open("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1.txt","r") as input: # Apro il file di testo
    with open("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1.txt","wb") as output: # Creo un nuovo file modificato
        for line in input:  
            print line # alvo tutte le linee diverse da # Constructed from....
            if line!="# Constructed from biom file"+"\n":   
                newline = line.replace('OTU ID', 'OTU_ID')
                output.write(newline)
                os.rename("/home/antonino/Scrivania/Prove_python/otu_table_filtered_L1_mod.txt",'result_otu_table_filtered_'+str(uuid.uuid4())+'.txt') 

这只适用于这种模式,但这不是我想要的。你知道吗


Tags: 文件fromtxtidhomelinetablefiltered