Python os.walk 来自当前目录

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])

对于所有其他 with as 语句类似

您可以使用 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                                            + " }" )

我不认为问题出在当前目录上,我认为问题出在您使用 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 文件的第一列包含从中获取值的文件夹的名称。