【问题标题】:Python - Read all files in a folder and create unique output for each filePython - 读取文件夹中的所有文件并为每个文件创建唯一的输出
【发布时间】:2017-03-30 03:49:31
【问题描述】:

我正在尝试将两个巨大的源文件(每行都有相应的内容)拆分为几个较小的文件,每个文件都包含唯一的输入,但到目前为止,事情已经结束。我正在考虑让一种方法读取输出目录中的所有文件并将其内容加入某个黑名单。所以起初,这个黑名单是空的,因为文件是空的,我想读取源文件并将n行复制到第一个较小的文件中,并将内容添加到黑名单中。接下来,我检查列表并将行写入第二个文件n 次,前提是它们不在所述黑名单上。出于某种原因,在我附加了第一次阅读的内容后,我没有收到任何输入到黑名单中。 这是我得到的:

def check_overlap(path):
# check if lines appear in other files

    content = []
    for filename in os.listdir(path):
        with open(path + filename, "r", encoding="utf-8") as f:
            content.append(f.read())
            print(filename + str(content))
            # when I print this out, it's empty for the first file
            # the other 3 files have the desired output, but why?
            # How is it empty after I appended the content of f?
            f.close()

    all_content = "".join(content)
    return all_content


def shuffle_data(n, source, output):
# shuffle source into n portions while keeping each line unique

    with open(output, "w", encoding="utf-8") as shuffled_file:

        existing_files = check_overlap()

        with open(source, 'r', encoding="utf-8") as source:
            i = 0
            for line in source:
                if i < n and line not in existing_files:
                    shuffled_file.write(line)
                    i += 1

shuffle_data(50, "source1", "output_50A")
shuffle_data(50, "source2", "output_50B")
shuffle_data(200, "source1", "output_200A")
shuffle_data(200, "source2", "output_200B")

这也意味着我得到了错误的整体输出。来源如下所示:

File 1    File 2
dog       dogs
book      books
horse     horses
flower    flowers
egg       eggs

他们必须保留相应的行,但由于我遇到的错误:

Output 1    Output 2
dog         dogs
book        books
horse       flowers
flowers     eggs

因此,由于黑名单不稳定,它似乎跳过了随机行。每次我运行程序时,源都是随机的,所以它们在哪一行开始分歧总是不同的。所有输出文件都在同一个目录中,源在不同的目录中。

【问题讨论】:

  • 你能从细节上退后一步,解释一下你想要完成的事情吗?似乎您想将输入文件分成一定长度的片段?如果是这样,有一个 unix 实用程序,split
  • 我有两个文件,我想将每个文件分成 50 行用于一个较小的文件,将 200 行用于另一个较小的文件。但是对于 200 行,我不希望从 50 行文件中重复任何行,因此为什么我尝试创建一个黑名单并且只放入以前文件中不存在的行。每个较小文件的行数各不相同。
  • 输入文件有多长? 250 行,还是别的什么?
  • 大约 90.000,需要为我生成 18 个文件
  • 平均每个文件有 5,000 行。效果如何?

标签: python directory


【解决方案1】:

根据 cmets,试试这样的方法。如果源文件在大小之前用完,您可能需要处理异常。

Sizes = [50, 100, 200, 600, 1000, 3000, 10000]


with open('file1') as f1:
    with open('file2') as f2:
        sources = iter(zip(f1, f2))

        for size in Sizes:
            o1_name = 'output_{}A'.format(size)
            o2_name = 'output_{}B'.format(size)
            with open(o1_name, 'w') as o1:
                with open(o2_name, 'w') as o2:
                    for _ in range(size):
                        l1,l2 = next(sources)
                        o1.write(l1.strip())
                        o2.write(l2.strip())

【讨论】:

    猜你喜欢
    • 1970-01-01
    • 2020-11-04
    • 2016-03-31
    • 1970-01-01
    • 2019-11-18
    • 1970-01-01
    • 1970-01-01
    • 2020-09-05
    • 1970-01-01
    相关资源
    最近更新 更多