【问题标题】:Python - loop through subdirectories with textual content on them and copy just a part on a text filePython - 遍历带有文本内容的子目录并仅复制文本文件中的一部分
【发布时间】:2016-02-15 18:00:55
【问题描述】:

我对 Python 很陌生,但这次我必须使用它! 这是我的问题:

我有一个名为“Test”目录。 在这个目录中有很多子目录,分别称为:“1”、“2”、“3”、“4”、“5”等。 在每个子目录中都有很多文本文件

我希望得到什么结果?

我应该能够遍历子目录并将内容分成 2 个单独的文件:test.txttrain.txt。必须为 每个 子目录执行此操作。

例如:

案例 1 --- 子目录 1 中的相关文本文件将是 test.txt 文件 --- 2-3-4-5-etc 子目录中的相关文本文件将是 train.txt

案例 2 --- 子目录 2 中的相关文本文件将是 test.txt --- 子目录 1-3-4-5-etc 中的相关文本文件将是 train.txt

案例 3 --- 子目录 3 中的相关文本文件将是 test.txt --- 子目录 1-2-4-5-etc 中的相关文本文件将是 train.txt 等等……

有没有简单的方法可以做到这一点?

【问题讨论】:

  • 您希望 目录test.txt?你到底是什么意思?
  • @zondo 正如我在目录中所写的,有许多文本文件。我不希望目录是 test.txt 而是目录本身的内容(目录中的文件)
  • 您想创建 2 个文件,并附加许多文件的内容?
  • @dawg 是的!所以在案例 1 中,我将使用子目录 1 的内容作为 test.file 以及子目录 2、3、4、5 等的内容。对于train.txt ...然后我将继续使用子目录2的内容作为test.file,以及1、3、4、5等。对于 train.txt ... 等等

标签: python loops iteration


【解决方案1】:

如果子目录下只有一个文件,可以这样试试(应该先把所有文件重命名为train.txt):

import glob,os
while True:
    # Your test case number
    trainnum=raw_input("Input test case number:\n")
    ftrain=open('train.txt','w')
    ftest=open('test.txt','w')
    for subdir in glob.iglob('*/'):
        # The subdirectory for test case
        if subdir.rstrip('/') == trainum):
           for fr in glob.iglob(subdir+os.sep+"*.*"):
                 with open(fr) as f:
                      ftest.write(f.read())
       else:
           for fr in glob.iglob(subdir+os.sep+"*.*"):
                 with open(fr) as f:
                      ftrain.write(f.read())
   ftest.close()
   ftrain.close()

如果子目录有很多文件,我不知道你要重命名哪个文件...

更新:只是一个例子。你应该进一步检查它。

【讨论】:

  • 问题是每个子目录下都有很多文本文件(400多个!)。我应该能够将该子目录的所有这些文本文件的内容放到一个名为“train.txt”的文件中
  • 你只想在Test目录下生成test.txttrain.txt文件?跨度>
  • 是的,相关子目录的内容每次都以正确的顺序排列
【解决方案2】:
#

Semi - Solution found

for i in range (1,4):
    print (i)
    for subdir, dirs, files in os.walk(rootdir):
        nb_dir = rootdir+str(i)
        if nb_dir == subdir:
            for file in files:
                f = open(os.path.join(subdir, file),'r')
                fcontent = f.readlines()
                ftest.write(str(fcontent)+"\n")

        else:
            for file in files:
                f = open(os.path.join(subdir, file),'r')
                fcontent = f.readlines()
                ftrain.write(str(fcontent))

test.txt
['Hello']
['World']
['!!!']

train.txt
['!!!']['World']['Hello']['!!!']['Hello']['World']

【讨论】:

    猜你喜欢
    • 2021-04-18
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2016-06-15
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    相关资源
    最近更新 更多