Разделить текстовый файл (построчно) на разные файлы - PullRequest
0 голосов
/ 31 августа 2018

Поиск разделителя данных построчно, используя python

  • RegEx
  • Содержать

В качестве примера файла "file" содержится:

X
X
Y
Z
Z
Z

Мне нужен чистый способ разбить этот файл на 3 разных, основанный на письме

Как образец:

def split_by_platform(FILE_NAME):

    with open(FILE_NAME, "r+") as infile:
        Data = infile.read()
        If the file contains "X"
            write to x.txt
        If the file contains "Y"
            write to y.txt
        If the file contains "Z"
            write to z.txt

x.txt файл будет выглядеть так:

X
X

y.txt Файл будет выглядеть так:

Y

z.txt файл будет выглядеть так:

Z
Z
Z

Ответы [ 3 ]

0 голосов
/ 31 августа 2018

Вот более общий способ сделать ту же работу:

from collections import Counter

with open("file.txt", "r+") as file:
    data = file.read().splitlines()
    counter = Counter(data)
    array2d = [[key, ] * value for key, value in counter.items()]
    print array2d # [['Y'], ['X', 'X'], ['Z', 'Z', 'Z']]
    for el in array2d:
        with open(str(el[0]) + ".txt", "w") as f:
            [f.write(e + "\n") for e in el]

Приведенный выше код сгенерирует X.txt, Y.txt и Z.txt с соответствующими значениями. Например, если у вас несколько букв C, код сгенерирует файл C.txt.

0 голосов
/ 31 августа 2018

РЕДАКТИРОВАТЬ благодаря @bruno desthuilliers, которые напомнили мне о правильном пути сюда:

Перебирать файловый объект (не «readlines»):

def split_by_platform(FILE_NAME, out1, out2, out3):

    with open(FILE_NAME, "r") as infile, open(out1, 'a') as of1, open(out2, 'a') as of2, open(out3, 'a') as of3:
        for line in infile:
            if "X" in line:
                of1.write(line)
            elif "Y" in line:
                of2.write(line)
            elif "Z" in line:
                of3.write(line)

РЕДАКТИРОВАТЬ с подсказкой @dim: Вот более общий подход для произвольной длины списка флаговых символов:

def loop(infilename, flag_chars):
    with open(infilename, 'r') as infile:
        for line in infile:
            for c in flag_chars:
                if c in line:
                    with open(c+'.txt', 'a') as outfile:
                        outfile.write(line)            
0 голосов
/ 31 августа 2018

Это должно сделать это:

with open('my_text_file.txt') as infile, open('x.txt', 'w') as x, open('y.txt', 'w') as y, open('z.txt', 'w') as z:
    for line in infile:
        if line.startswith('X'):
            x.write(line)
        elif line.startswith('Y'):
            y.write(line)
        elif line.startswith('Z'):
            z.write(line)
Добро пожаловать на сайт PullRequest, где вы можете задавать вопросы и получать ответы от других членов сообщества.
...