Python os.walk from current directory



如何编辑此脚本,它将从当前目录运行。如果我像现在一样运行脚本,则会收到错误,指出它找不到我指定的文件。我的感觉是os.walk没有在当前目录的子文件夹中搜索。我不想指定路径名,因为我想在不同的目录中运行此脚本。综上所述;请帮助我更改此脚本,它将从当前目录运行并查找当前目录子文件夹中的文件。谢谢!

import os
import csv
from itertools import chain
from collections import defaultdict

for root, dirs, files in os.walk('.'):
    d1 = {}
    with open (os.path.join(root, 'genes.gff.genespercontig.csv'), 'r') as f1:
        for line in f1:
            ta = line.split()
            d1[ta[1]] = int(ta[0])
    d2 = {}
    with open(os.path.join(root, 'hmmer.analyze.txt.result.txt'), 'r') as f2:
        for line in f2:
            tb = line.split()
            d2[tb[1]] = int(tb[0])
    d3 = defaultdict(list)
    for k, v in chain(d1.items(), d2.items()):
        d3[k].append(v)
    with open(os.path.join(root, 'output_contigsvsgenes.csv'), 'w+') as fnew:
            writer = csv.writer(fnew)     
            for k,v in d3.items(): 
                writer.writerow([k] + v) 
import os
os.getcwd() #return the current working directory

因此,在您的情况下,循环更改为:

for root, dirs, files in os.walk(os.getcwd()): 

在您的情况下,您可能还必须检查该文件是否存在:

if os.path.isfile(os.path.join(root, 'genes.gff.genespercontig.csv')):
    with open (os.path.join(root, 'genes.gff.genespercontig.csv'), 'r') as f1:
        for line in f1:
            ta = line.split()
            d1[ta[1]] = int(ta[0])

同样,对于所有其他带有 as 语句的语句

我不

认为问题在当前目录中工作,我认为问题在于您使用os.walk的方式。在开始使用它们之前,您应该检查这些文件是否存在,我认为可能会发生错误,因为第一个root文件夹是当前工作目录。不过,我们可以将其重新排列为一个函数,如下所示:

import os
import csv
from itertools import chain
from collections import defaultdict

def get_file_values(find_files, output_name):
    for root, dirs, files in os.walk(os.getcwd()):
        if all(x in files for x in find_files):
            outputs = []
            for f in find_files:
                d = {}
                with open(os.path.join(root, f), 'r') as f1:
                    for line in f1:
                        ta = line.split()
                        d[ta[1]] = int(ta[0])
                outputs.append(d)
            d3 = defaultdict(list)
            for k, v in chain(*(d.items() for d in outputs)):
                d3[k].append(v)
            with open(os.path.join(root, output_name), 'w+') as fnew:
                writer = csv.writer(fnew)
                for k, v in d3.items():
                    writer.writerow([k] + v)
get_file_values(['genes.gff.genespercontig.csv', 'hmmer.analyze.txt.result.txt'], 'output_contigsvsgenes.csv')

没有您的数据,我无法对此进行测试,尽管我认为它应该有效。

编辑

要获取输出 csv 文件的每一行中包含的文件夹,我们可以将调用更改为 writer.writerow 一点,为:

writer.writerow([root, k] + v)

因此,创建的每个 csv 文件的第一列包含从中获取值的文件夹的名称。

您可以使用

os.getcwd()来获取当前目录(调用脚本时所在的目录(,但最好将目标目录作为参数传递。

在 Python 脚本中,有许多选项允许深入回顾,以便更好地定位脚本运行的环境。当前目录可通过

os.getcwd((

您在评论中建议,要处理的文件不在当前目录中,而是在子目录中。在这种情况下,像这样调整脚本(将循环的整个块更深地移动到for dir in dirs:中,并相应地调整os.path.join()(:

for root, dirs, files in os.walk(os.getcwd()):
    for dir in dirs: 
        print(os.path.join(root, dir, 'genes.gff.genespercontig.csv'))

只是为了好玩,下面简要概述了有关 Python 脚本运行环境的其他一些有用见解:

import __future__    
import os, sys
print( "Executable running THIS script    : { " + sys.executable                                          + " }" )
print( "Full path file name of THIS script: { " + os.path.realpath(__file__)                              + " }" )
print( "Full path directory to THIS script: { " + os.path.dirname(os.path.abspath(__file__))              + " }" )
print( "Current working directory         : { " + os.getcwd()                                             + " }" )
print( "Has THIS file started Python?     : { " + { True: "Yes", False: "No" }[(__name__ == "__main__")]  + " }" )
print( "Which Python version is running?  : { " + sys.version.replace("n", "")                           + " }" )
print( "Which operating system is there?  : { " + sys.platform                                            + " }" )

相关内容

最新更新