2014-10-11 194 views
1

我有一个包含在这个名称格式不同的子目录的文件名列表的txt文件列表写入输出到子目录的位置中的文件通过文件名列表中的行并产生适当的输出。根据输入文件路径的

我想要的是将具有不同名称的文件的输出保存在与文件名列表中提供的路径对应的目录中。

我写的代码指示(对于每个for回路1)目录中的从该脚本在命令行作为这样的” shell$ python script.py inputfilelist.txt

运行所有的输出这是我的脚本:

import sys 

with open(sys.argv[1]) as f: 
    for filename in f: 
     with open(filename.strip().strip("\n"),'a') as f1: 
      #print f1 
      output = [] 
      outfilename = filename.strip("\n").lstrip("./").replace("/", "__") + "out.txt" 
      #print outfilename 
      with open(outfilename, 'a') as outfile: 
       line = f1.readline() 
       while line and not line.startswith('GO-ID'): 
        line = f1.readline() 
       data = f1.readlines() 
       for line in data: 
        line = line.split("\t") 
        GOnr = line[0].lstrip("\s") 
        pvalue = line[1].strip() 
        corrpval = float(line[2].strip()) 
        if corrpval <= 0.05: 
         outstring = "GO:"+"%s %s" % (GOnr, str(corrpval)) 
         outfile.write(outstring + "\n") 
         #print outstring 

我正在寻找最简单的方法让每个循环保存其在OUTFILE相同的文件名的输入路径的位置。

想我必须使用sys模块,b ut阅读python提供的解释,我不太明白如何使用sys.stdinsys.stdout函数。

相反,我一直在试图通过定义一个函数upfront来重新格式化文件列表中的输入目录,为每个新的out.txt文件生成完整路径。

def output_name(input_file): 
    file_line=inputfile.strip() 
    line_as_list=file_line.split("/") 
    line_as_list.append("out.txt")  # file name 
    line_as_list.remove(line_as_list[-2]) # remove file name of input file from path      description 
    full_output_name="/".join(line_as_list) #join to add leading and intermittent `/` 
    return full_output_name 

当我交互运行这段代码,它做什么,它需要太多,如:outputname("./A_blurb/test.txt") == "./A_blurb/out.txt" 然而,当我在命令行中运行它,我得到这个消息:return full_output_name \n SyntaxError: 'return' outside function

我仔细检查缩进但无法找到这个错误消息的原因是什么.... 谢谢。

+0

请告诉我们您的代码。 – Alfe 2014-10-11 20:59:44

回答

0

您的脚本将文件保存到从输入路径推导出的输出路径。

没关系。您不应该尝试同时读取和重写文件。这很复杂。创建另一个文件,然后移动它以覆盖原始文件更容易。

尝试os.rename()(或者shutil.move(),也在标准库):

# After closing the output file and the input file 
os.rename(temporary_output_path, input_path) 
+0

嗨,不太清楚,如果我明白。与您所说的相反,代码将文件保存在我从中运行脚本的路径中,而不是从输入路径中推演出的输出目录中。 – oaklander114 2014-10-11 21:25:58

+0

我以为您想重写原始文件。如果你只是想将它们保存到一个相对路径,可以尝试使用'os.path.join()'和该模块中的其他函数。 – slezica 2014-10-11 21:27:43

0

在问题结束时的代码实际上是工作的罚款。所以下面是我的问题的工作答案。

鉴于通过

string = """" 
./A_blurb/test.txt 
./B_foo/bar.txt 
./B_foo/bric.txt 
""" 

下面的函数的文件循环的此列表生成相同的格式串的列表,但除去file.txt和添加out

def output_name(name_in): 
    file_line = name_in.strip() 
    line_as_list = file_line.split("/") 
    line_as_list.append("out.txt")  ## generate file name 
    line_as_list.remove(line_as_list[-2]) ## remove the file name 
    full_output_name="/".join(line_as_list) # join fields in the list with `/` 
    return full_output_name # return the re-formatted file path 

这是输出:

./A_blurb/out.txt 
./B_foo/out.txt 
./B_foo/out.txt 

主要代码然后遍历这个列表并使用每行作为open(outfilename, 'w')的名称,结果是'out.txt'文件被写入相应的目录中,作为输入到脚本中的地方。