Neculai Fântânaru

Everything Depends On The Leader

Python: Split All Text Files In A Folder Into Smaller Text Files

On May 05, 2021
, in
Python Scripts Examples by Neculai Fantanaru

You can view the full code here: https://pastebin.com/k2wpUwb2

Install Python.

Make a folder: fisiere_impartite ( Resized files will be stored here )

CODE:

import sys
import os
import nltk
from nltk import tokenize

def read_text_from_file(file_path):
    """
    Aceasta functie returneaza continutul unui fisier.
    file_path: calea catre fisierul din care vrei sa citesti
    """
    with open(file_path, encoding='utf8') as f:
        text = f.read()
        return text


def write_to_file(text, file_path):
    """
    Aceasta functie scrie un text intr-un fisier.
    text: textul pe care vrei sa il scrii
    file_path: calea catre fisierul in care vrei sa scrii
    """
    with open(file_path, 'wb') as f:
        f.write(text.encode('utf8', 'ignore'))

def imparte_fisiere(cale_fisier_txt, cale_folder_fisiere_impartite):
    text = read_text_from_file(cale_fisier_txt)
    propozitii = tokenize.sent_tokenize(text)
    nume_fisier = os.path.basename(cale_fisier_txt).split('.')[0] # "30.txt" => split('.') => ["30", "txt"] => [0] => "30"
    chunk = ''
    chunk_size = 5000 # 5KB
    chunk_number = 1
    for propozitie in propozitii:
        if len(chunk.encode('utf-8')) < chunk_size:
            chunk = chunk + " " + propozitie
        else:
            # scriere fisier
            cale_fisier_rezultat = cale_folder_fisiere_impartite + '\\' + nume_fisier + "_" + str(chunk_number) + ".txt" # => "30_1.txt"
            write_to_file(chunk, cale_fisier_rezultat)
            # print("Fisierul {} a fost scris cu succes.".format(nume_fisier + "_" + str(chunk_number) + ".txt"))
            chunk = propozitie
            chunk_number += 1

def creare_fisiere(cale_folder_txt, cale_folder_fisiere_impartite):
    """
    Functia itereaza printr-un folder care contine fisiere txt si imparte in 5KB fiecare fisier
    """
    count = 0
    for f in os.listdir(cale_folder_txt):
            if f.endswith('txt'):
                cale_fisier_txt = cale_folder_txt + "\\" + f
                imparte_fisiere(cale_fisier_txt, cale_folder_fisiere_impartite)
                count += 1
            else:
                continue
    print("Numarul de fisiere modificate: ", count)

# cale_folder_txt/30.txt => cale_folder_fisiere_impartite/30_part1.txt
#                        => cale_folder_fisiere_impartite/30_part2.txt

def main():
    creare_fisiere("c:\\Folder1", "c:\\Folder1\\fisiere_impartite")

if __name__ == '__main__':
    main()
  

That's all folks.

If you like my code, then make me a favor: translate your website into Romanian, "ro".

Also, see this VERSION 2 or VERSION 3 or VERSION 4 or VERSION 5 or VERSION 6 or VERSION 7

Alatura-te Comunitatii Neculai Fantanaru
The 63 Greatest Qualities of a Leader
Cele 63 de calităţi ale liderului

Why read this book? Because it is critical to optimizing your performance. Because it reveals the main coordinates after that are build the character and skills of the leaders, highlighting what it is important for them to increase their influence.

Leadership - Magic of Mastery
Atingerea maestrului

The essential characteristic of this book in comparison with others on the market in the same domain is that it describes through examples the ideal competences of a leader. I never claimed that it's easy to become a good leader, but if people will...

The Master Touch
Leadership - Magia măiestriei

For some leaders, "leading" resembles more to a chess game, a game of cleverness and perspicacity; for others it means a game of chance, a game they think they can win every time risking and betting everything on a single card.

Leadership Puzzle
Leadership Puzzle

I wrote this book that conjoins in a simple way personal development with leadership, just like a puzzle, where you have to match all the given pieces in order to recompose the general image.

Performance in Leading
Leadership - Pe înţelesul tuturor

The aim of this book is to offer you information through concrete examples and to show you how to obtain the capacity to make others see things from the same angle as you.

Leadership for Dummies
Leadership - Pe înţelesul tuturor

Without considering it a concord, the book is representing the try of an ordinary man - the author - who through simple words, facts and usual examples instills to the ordinary man courage and optimism in his own quest to be his own master and who knows... maybe even a leader.