Python 通过多个文件夹连接多个文件

Python 通过多个文件夹连接多个文件,python,file-io,Python,File Io,我试图创建一个单一的文件中的多个文本文件,我有多个文件夹。这是我用来连接的代码。仅当程序文件放置在每个文件夹中时,它才起作用: import os file_list = [each for each in cur_folder if each.endswith(".txt")] print file_list align_file = open("all_the_files.txt","w") seq_lis

我试图创建一个单一的文件中的多个文本文件,我有多个文件夹。这是我用来连接的代码。仅当程序文件放置在每个文件夹中时,它才起作用:

        import os

        file_list = [each for each in cur_folder if each.endswith(".txt")]
        print file_list

        align_file = open("all_the_files.txt","w")

        seq_list = []

        for each_file in file_list:
                f_o = open(file_path,"r")
                seq = (f_o.read().replace("\n",""))
                lnth = len(seq)
                wholeseq = ">"+each_file+" | "+str(lnth)+" nt\n"+seq+"\n"
                align_file.write(wholeseq)
                print "done" 
现在我尝试编辑,以确保它自动运行整个
Data
文件夹,然后进入子目录并连接所有文件,而无需将程序文件粘贴到每个文件夹中。这是编辑

    import os

    dir_folder = os.listdir("C:\Users\GAMER\Desktop\Data")

    for each in dir_folder:
            cur_folder = os.listdir("C:\\Users\\GAMER\\Desktop\\Data\\"+each)
            file_list = []

            file_list = [each for each in cur_folder if each.endswith(".txt")]
            print file_list

            align_file = open("all_the_files.txt","w")

            seq_list = []

            for each_file in file_list:

                f_o = open(file_path,"r")
                seq = (f_o.read().replace("\n",""))
                lnth = len(seq)
                wholeseq = ">"+each_file+" | "+str(lnth)+" nt\n"+seq+"\n"
                align_file.write(wholeseq)
                print "done" , cur_folder
然而,当我运行这个程序时,我在文件夹的第一个文件上得到一个错误,说没有这样的文件存在。我似乎能理解为什么,特别是因为它命名的文件不是“硬编码的”。任何帮助都将不胜感激


如果代码看起来很难看,你可以自由地提出更好的方法

Jamie是正确的-os.walk很可能是您需要的功能

基于您的用例的示例:

for root, dirs, files in os.walk(r"C:\Users\GAMER\Desktop\Data"):
    for f in files:
        if f.endswith('.txt'):
            print(f)
这将打印在os.walk中传递的根目录中每个文件夹中的每个文件的名称,只要文件名以.txt结尾


Python的文档在这里:

请看一下,确保您知道自己正在重新发明轮子:@goncalopp cat是unix-他的文件路径表明他在Windows上。