从文件夹中读取所有文件并编辑

时间:2016-03-17 09:50:27

标签: python readfile

我正在尝试从test文件夹中读取所有fasta文件,并将文件名放在单个文件的所有标头中。用于第一个文件的代码,不进入第二个文件并返回错误。你能帮我找到我的代码中的错误或编辑它吗?感谢

import sys, glob, os, string
header = ''
check = 0
path = "./test/"
dirs = os.listdir(path)
for file in dirs:
    fp = open(file, "r")
    fpx = open('%s_output.txt' % file, 'w')
    for line in fp:
        if line.startswith('>'):
            line = line.rstrip()
            check = check + 1
            if check >= 1:
                header = line
                fpx.write(header + '_' + file + '\n')
        else:
            line = line.rstrip()
            fpx.write(line + '\n')

1 个答案:

答案 0 :(得分:0)

提供您收到的错误消息会很好!我认为这必须以“找不到文件”失败,因为您尝试按名称而不是路径打开文件。试试fp = open(os.path.join(path, file), "r")

import sys, glob, os, string
header = ''
check = 0
path = "./test/"
dirs = os.listdir(path)
for file in dirs:
    fp = open(os.path.join(path, file), "r")
    fpx = open('%s_output.txt' % file, 'w')
    for line in fp:
        if line.startswith('>'):
            line = line.rstrip()
            check = check + 1
            if check >= 1:
                header = line
                fpx.write(header + '_' + file + '\n')
        else:
            line = line.rstrip()
            fpx.write(line + '\n')