কম্পিউটার টিউটোরিয়াল

পাইথনে LINECACHE মডিউল ব্যবহার করে টেক্সট ফাইল পড়া

সমাধান

linecache মডিউল ক্যাশে বাস্তবায়ন করে যা ফাইল কন্টেন্টগুলোর লাইন ভাগ করে মেমরিতে রাখে। linecache লিস্টে ইনডেক্সিং দিয়ে লাইন ফেরত দেয় এবং বারবার ফাইল পড়ে লাইন পার্স করার চেয়ে সময় বাঁচায়।

linecache মডিউল একই ফাইল থেকে একাধিক লাইন খুঁজে বের করার জন্য খুব উপযোগী।

উদাহরণ

import os
import tempfile
import linecache

text = """Lorem ipsum dolor sit amet..."""

# ১. টেম্পোরারি ফাইল তৈরি ও ক্লিনআপ ফাংশন
def make_tempfile():
    """Function: Create a temporary file.
    return: Temp file name."""
    fd, temp_file = tempfile.mkstemp()
    os.close(fd)
    with open(temp_file, 'wt') as f:
        f.write(text)
    return temp_file

def cleanup(temp_file):
    os.unlink(temp_file)

# ২. নির্দিষ্ট লাইন পড়ুন linecache দিয়ে
# লাইন নম্বর ১ থেকে শুরু হয় (লিস্টের মত ০ থেকে নয়)
filename = make_tempfile()
print(f"Output \n {filename}")

split_line = '\n'
# সোর্স থেকে সরাসরি ৫ম লাইন
print(f"*** Displaying first 5 lines directly from the source \n {text.split(split_line)[4]}" )
# ক্যাশ থেকে ৫ম লাইন
print(f" \n *** Displaying first 5 lines from the cache \n {linecache.getline(filename, 5)}" )

cleanup(filename)

আউটপুট

*** Displaying first 5 lines directly from the source
Id porro facete cum. No est veritus detraxit facilisis...
*** Displaying first 5 lines from the cache
Id porro facete cum. No est veritus detraxit facilisis...

৪. ব্ল্যাঙ্ক লাইন হ্যান্ডলিং

linecache সবসময় লাইনের শেষে নিউলাইন রাখে। তাই লাইন খালি হলে শুধু নিউলাইন ফেরত দেয়।

import linecache
filename = make_tempfile()
print(f"Output \n {filename}")
print(f"\n *** The number of lines in the text is 13.")
print(" \n *** Displaying the lastline from Linecache which should be a new line\n {!r}".format(linecache.getline(filename, 8)) )
cleanup(filename)

আউটপুট

*** The number of lines in the text is 13.
*** Displaying the lastline from Linecache which should be a new line
'\n'

৫. উপসংহার

যখন অ্যাপ্লিকেশনে ফাইলগুলোর র‍্যান্ডম অ্যাক্সেস দরকার হয়, linecache লাইন নম্বর দিয়ে লাইন পড়ার কাজ সহজ করে দেয়। ফাইল কন্টেন্ট ক্যাশে থাকার কারণে মেমরি খপত এর ওপর সতর্ক থাকতে হবে।

  1. Tkinter-এ পাইথন ব্যবহার করে ফোল্ডার থেকে একাধিক টেক্সট ফাইল পড়া

  2. পাইথনে টেক্সট ফাইল পড়ার পদ্ধতি

  3. পাইথনে PDF ফাইল এক্সেল ফাইলে কনভার্ট করা

  4. পাইথনে পাওয়ারপয়েন্ট ফাইল তৈরি করা