Hướng dẫn how do you cut a text file in python? - làm thế nào để bạn cắt một tệp văn bản trong python?

Dưới đây là tập lệnh Python bạn có thể sử dụng để phân tách các tệp lớn bằng subprocess:

Show
"""
Splits the file into the same directory and
deletes the original file
"""

import subprocess
import sys
import os

SPLIT_FILE_CHUNK_SIZE = '5000'
SPLIT_PREFIX_LENGTH = '2'  # subprocess expects a string, i.e. 2 = aa, ab, ac etc..

if __name__ == "__main__":

    file_path = sys.argv[1]
    # i.e. split -a 2 -l 5000 t/some_file.txt ~/tmp/t/
    subprocess.call(["split", "-a", SPLIT_PREFIX_LENGTH, "-l", SPLIT_FILE_CHUNK_SIZE, file_path,
                     os.path.dirname(file_path) + '/'])

    # Remove the original file once done splitting
    try:
        os.remove(file_path)
    except OSError:
        pass

Bạn có thể gọi nó bên ngoài:

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))

Bạn cũng có thể nhập subprocess và chạy trực tiếp trong chương trình của mình.

Vấn đề với phương pháp này là cách sử dụng bộ nhớ cao: subprocess tạo ra một cái nĩa có dấu chân bộ nhớ có cùng kích thước với quy trình của bạn và nếu bộ nhớ quy trình của bạn đã nặng, nó sẽ tăng gấp đôi nó trong thời gian nó chạy. Điều tương tự với

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
2.

Dưới đây là một cách Python thuần túy khác, mặc dù tôi chưa thử nghiệm nó trên các tệp khổng lồ, nó sẽ chậm hơn nhưng hãy nghiêng về bộ nhớ:

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here

Dưới đây là một ví dụ khác sử dụng

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
3:

"""
Simple example using readlines()
where the 'file' is generated via:
seq 10000 > file
"""
CHUNK_SIZE = 5


def yield_rows(reader, chunk_size):
    """
    Yield row chunks
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk


def batch_operation(data):
    for item in data:
        print(item)


with open('file', 'r') as f:
    chunks = yield_rows(f.readlines(), CHUNK_SIZE)
    for _chunk in chunks:
        batch_operation(_chunk)

Ví dụ Readlines trình bày cách tạo dữ liệu của bạn để truyền các khối để hoạt động mà mong đợi các khối. Thật không may, các lần đọc mở ra toàn bộ tệp trong bộ nhớ, tốt hơn là sử dụng ví dụ đầu đọc cho hiệu suất. Mặc dù nếu bạn có thể dễ dàng phù hợp với những gì bạn cần vào bộ nhớ và cần xử lý nó trong các khối này thì đủ.

Trong bài viết này, chúng ta sẽ xem cách chia một tệp thành một danh sách trong Python. & NBSP;

Khi chúng tôi muốn từng dòng của tệp được liệt kê tại các vị trí liên tiếp trong đó mỗi dòng trở thành một phần tử trong tệp, phương thức splutLines () hoặc rstrip () được sử dụng để chia tệp thành một danh sách. Hãy cùng xem một vài ví dụ để xem nó đã thực hiện như thế nào.

Ví dụ 1: Sử dụng Splitlines ()splitlines()

Tệp được mở bằng phương thức Open () trong đó đối số đầu tiên là đường dẫn tệp và đối số thứ hai là chuỗi (chế độ) có thể là 'r', 'w', v.v. tập tin hoặc được ghi vào tệp. Ở đây khi chúng tôi đọc chế độ tệp là ‘r. Phương thức Read () đọc dữ liệu từ tệp được lưu trữ trong biến File_Data. Phương thức splitlines () chia dữ liệu thành các dòng và trả về một đối tượng danh sách. Sau khi in ra danh sách, tệp được đóng bằng phương thức đóng ().

Tạo một tệp văn bản có tên là Assign AssentIle.txt, như được hiển thị trong hình ảnh bên dưới được sử dụng làm đầu vào.

Python3

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
4
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
0
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
1

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
2
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
4

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
7

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
9

"""
Simple example using readlines()
where the 'file' is generated via:
seq 10000 > file
"""
CHUNK_SIZE = 5


def yield_rows(reader, chunk_size):
    """
    Yield row chunks
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk


def batch_operation(data):
    for item in data:
        print(item)


with open('file', 'r') as f:
    chunks = yield_rows(f.readlines(), CHUNK_SIZE)
    for _chunk in chunks:
        batch_operation(_chunk)
0

Output:

['This is line 1,', 'This is line 2,', 'This is line 3,']

Ví dụ 2: Sử dụng rstrip ()

Trong ví dụ này thay vì sử dụng phương thức splutLines () phương thức rstrip () được sử dụng. Phương thức rstrip () loại bỏ các ký tự dấu vết. Nhân vật kéo dài được đưa ra trong ví dụ này là ‘\ n, đó là dòng mới. Đối với các phương thức Loop và Strip () được sử dụng để chia tệp thành một danh sách các dòng. Các tập tin được đóng ở cuối.

Python3

import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
4
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
0
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
1

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
2
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
4

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
9

"""
Simple example using readlines()
where the 'file' is generated via:
seq 10000 > file
"""
CHUNK_SIZE = 5


def yield_rows(reader, chunk_size):
    """
    Yield row chunks
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk


def batch_operation(data):
    for item in data:
        print(item)


with open('file', 'r') as f:
    chunks = yield_rows(f.readlines(), CHUNK_SIZE)
    for _chunk in chunks:
        batch_operation(_chunk)
0

Output:

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]

CHUNK_SIZE = 5000 def yield_csv_rows(reader, chunk_size): """ Opens file to ingest, reads each line to return list of rows Expects the header is already removed Replacement for ingest_csv :param reader: dictReader :param chunk_size: int, chunk size """ chunk = [] for i, row in enumerate(reader): if i % chunk_size == 0 and i > 0: yield chunk del chunk[:] chunk.append(row) yield chunk with open(local_file_path, 'rb') as f: f.readline().strip().replace('"', '') reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"') chunks = yield_csv_rows(reader, CHUNK_SIZE) for chunk in chunks: if not chunk: break # Do something with your chunk here 5import os fs_result = os.system("python file_splitter.py {}".format(local_file_path)) 5 CHUNK_SIZE = 5000 def yield_csv_rows(reader, chunk_size): """ Opens file to ingest, reads each line to return list of rows Expects the header is already removed Replacement for ingest_csv :param reader: dictReader :param chunk_size: int, chunk size """ chunk = [] for i, row in enumerate(reader): if i % chunk_size == 0 and i > 0: yield chunk del chunk[:] chunk.append(row) yield chunk with open(local_file_path, 'rb') as f: f.readline().strip().replace('"', '') reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"') chunks = yield_csv_rows(reader, CHUNK_SIZE) for chunk in chunks: if not chunk: break # Do something with your chunk here 7

Ví dụ 2: Sử dụng rstrip ()

Python3

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
1
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
6
[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
7

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
['This is line 1,', 'This is line 2,', 'This is line 3,']
4
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
6
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
2

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
4
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
6

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
9

Output:

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']

Ví dụ 4: Tách tệp văn bản với trình tạo

Một máy phát điện trong Python là một mẹo đặc biệt có thể được sử dụng để tạo ra một mảng. Một trình tạo, giống như một hàm, trả về một mảng một mục tại một thời điểm. Từ khóa năng suất được sử dụng bởi các máy phát điện. Khi Python gặp phải một câu lệnh năng suất, nó sẽ lưu trạng thái chức năng cho đến khi trình tạo được gọi lại sau. Từ khóa năng suất đảm bảo rằng trạng thái của chúng tôi trong khi vòng lặp được lưu giữa các lần lặp. Khi xử lý các tệp lớn, điều này có thể hữu ích

Python3

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
1

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
6
[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
6
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
1

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
1
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
2

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
7

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
9 subprocess0 subprocess1

subprocess2

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3subprocess4

subprocess2subprocess6

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3subprocess8 subprocess9

['This is line 1,', 'This is line 2,', 'This is line 3,']
4
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
08

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
11

Output:

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']

Ví dụ 5: Sử dụng danh sách hiểu

Danh sách Python Hiểu là một cách tuyệt vời để làm việc với các danh sách. Danh sách toàn diện là mạnh mẽ và chúng có cú pháp ngắn hơn. & nbsp; Hơn nữa, các câu lệnh hiểu danh sách thường dễ đọc hơn.

Để đọc các tệp văn bản trong các ví dụ trước, chúng tôi đã phải sử dụng một vòng lặp. Sử dụng khả năng hiểu danh sách, chúng tôi có thể thay thế cho Loop của chúng tôi bằng một dòng mã duy nhất. Sau khi lấy dữ liệu thông qua việc hiểu danh sách, & nbsp; split () được sử dụng & nbsp; để tách các dòng và nối & nbsp; chúng vào danh sách mới. Hãy cùng xem một ví dụ để hiểu.
After obtaining the data through list comprehension,  the split() is used to separate the lines and append them to a new list. let’s see an example to understand.

Python3

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
1
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
18
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
2

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
4
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
24
['This is line 1,', 'This is line 2,', 'This is line 3,']
4
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
6

CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
9

['This is line 1,', 'This is line 2,', 'This is line 3,']
4
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
08

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
CHUNK_SIZE = 5000

def yield_csv_rows(reader, chunk_size):
    """
    Opens file to ingest, reads each line to return list of rows
    Expects the header is already removed
    Replacement for ingest_csv
    :param reader: dictReader
    :param chunk_size: int, chunk size
    """
    chunk = []
    for i, row in enumerate(reader):
        if i % chunk_size == 0 and i > 0:
            yield chunk
            del chunk[:]
        chunk.append(row)
    yield chunk

with open(local_file_path, 'rb') as f:
    f.readline().strip().replace('"', '')
    reader = unicodecsv.DictReader(f, fieldnames=header.split(','), delimiter=',', quotechar='"')
    chunks = yield_csv_rows(reader, CHUNK_SIZE)
    for chunk in chunks:
        if not chunk:
            break
        # Do something with your chunk here
8
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
11

Output:

['This is line 1,', 'This is line 2,', 'This is line 3,']
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']

Ví dụ 5: Sử dụng danh sách hiểu

Danh sách Python Hiểu là một cách tuyệt vời để làm việc với các danh sách. Danh sách toàn diện là mạnh mẽ và chúng có cú pháp ngắn hơn. & nbsp; Hơn nữa, các câu lệnh hiểu danh sách thường dễ đọc hơn.

Để đọc các tệp văn bản trong các ví dụ trước, chúng tôi đã phải sử dụng một vòng lặp. Sử dụng khả năng hiểu danh sách, chúng tôi có thể thay thế cho Loop của chúng tôi bằng một dòng mã duy nhất. Sau khi lấy dữ liệu thông qua việc hiểu danh sách, & nbsp; split () được sử dụng & nbsp; để tách các dòng và nối & nbsp; chúng vào danh sách mới. Hãy cùng xem một ví dụ để hiểu.

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
8
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
4
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
5
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
24
['This is line 1,', 'This is line 2,', 'This is line 3,']
4
['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
0
['This is line 1,', 'This is line 2,', 'This is line 3,']
6

Python3

Ví dụ 6: Chia một tệp văn bản duy nhất thành nhiều tệp văn bản

Nếu chúng tôi có một tệp lớn và xem tất cả dữ liệu trong một tệp là khó khăn, chúng tôi có thể chia dữ liệu thành nhiều tệp. Hãy để xem một ví dụ trong đó chúng tôi chia dữ liệu tệp thành hai tệp.

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
1
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
56
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
58
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
59

Cắt danh sách Python có thể được sử dụng để phân chia danh sách. Để bắt đầu, chúng tôi đọc tệp với phương thức readlines (). Tệp nửa đầu/nửa trên sau đó được sao chép vào một tệp mới có tên là nửa đầu.txt. Trong vòng này, chúng tôi sẽ sử dụng Danh sách cắt để viết nửa đầu của tệp chính & NBSP;

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
73

[['This is line 1,'], ['This is line 2,'], ['This is line 3,']]
1
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
6
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
7
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
77
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
9
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
58
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
80

Một vòng lặp thứ hai được sử dụng để ghi phần khác của dữ liệu vào tệp thứ hai. Nửa thứ hai của dữ liệu được chứa trong nửa sau.txt. Để thực hiện lát cắt, chúng ta cần sử dụng phương thức Len () để xác định số lượng dòng trong tệp chính, phương thức int () được sử dụng để chuyển đổi kết quả phân chia thành giá trị số nguyên

['This', 'is', 'line', '1,']
['This', 'is', 'line', '2,']
['This', 'is', 'line', '3,']
3
import os
fs_result = os.system("python file_splitter.py {}".format(local_file_path))
94

Output:

Hướng dẫn how do you cut a text file in python? - làm thế nào để bạn cắt một tệp văn bản trong python?


Làm thế nào để bạn cắt một tệp văn bản trong Python?

Chuỗi trang trí Python..
Dải (): Trả về một chuỗi mới sau khi loại bỏ bất kỳ không gian trắng dẫn đầu và dấu vết bao gồm các tab (\ t) ..
RSTRIP (): Trả về một chuỗi mới với khoảng trắng kéo dài. ....
Lstrip (): Trả về một chuỗi mới với khoảng trắng hàng đầu bị loại bỏ hoặc loại bỏ khoảng trắng khỏi phía bên trái của chuỗi ..

Làm cách nào để phân chia một tệp văn bản?

Làm thế nào để chia một tài liệu TXT trực tuyến..
Chọn và tải lên tài liệu TXT của bạn để chia tách ..
Chỉ định số trang mong muốn và nhấp vào nút chia ngay bây giờ ..
Khi tài liệu TXT của bạn được chia nhỏ, nhấp vào nút tải xuống ..
Sử dụng nút email để gửi liên kết tải xuống qua email ..

Làm thế nào để bạn chia một tập tin trong Python?

Phương thức Split () trong Python trả về một danh sách các từ trong chuỗi/dòng, được phân tách bằng chuỗi phân cách.Phương pháp này sẽ trả về một hoặc nhiều chuỗi mới.Tất cả các chuỗi con được trả về trong danh sách DataType.

Làm thế nào để chia () hoạt động trong Python?

Phương thức chia () chia một chuỗi vào một danh sách.Bạn có thể chỉ định phân tách, dấu phân cách mặc định là bất kỳ khoảng trắng nào.Lưu ý: Khi MaxSplit được chỉ định, danh sách sẽ chứa số lượng phần tử được chỉ định cộng với một.splits a string into a list. You can specify the separator, default separator is any whitespace. Note: When maxsplit is specified, the list will contain the specified number of elements plus one.