Question: My below Python code is not initiating multiple threads, kindly identify the problem: ## Start of Python Script import os import math import concurrent.futures #

My below Python code is not initiating multiple threads, kindly identify the problem:

## Start of Python Script

import os

import math

import concurrent.futures

# function to process each chunk

def process_chunk(chunk_num, chunk_lines):

with open("chunk{}.txt".format(chunk_num), "w") as f1: # it will write the lines of the chunk to a file

for l in chunk_lines:

f1.write(l)

with open("chunk{}.txt".format(chunk_num), "r") as f1: # first of all open the file in read mode

all_lines = f1.readlines()

with open("output{}.txt".format(chunk_num), "w") as f2:

for l in all_lines:

dn = int(l) * 2 # it will calculate double of the number

f2.write(str(dn) + ' ') # it will write the result to output file

os.remove("chunk{}.txt".format(chunk_num)) # remove the chunk file

# read the input file

with open("file34.txt", "r") as f:

lines = f.readlines()

# calculate number of lines per chunk

num_lines = len(lines)

lines_per_chunk = math.ceil(num_lines / 5) # will handle case where the number of lines is not perfectly divisible by 5

# divide the input file into chunks

chunks = [lines[i:i + lines_per_chunk] for i in range(0, num_lines, lines_per_chunk)]

# process each chunk concurrently

with concurrent.futures.ThreadPoolExecutor() as executor:

for i, chunk in enumerate(chunks):

executor.submit(process_chunk, i, chunk)

# combine the output files

with open("output.txt", "w") as out_file:

for i in range(5):

with open("output{}.txt".format(i), "r") as f:

out_file.write(f.read())

os.remove("output{}.txt".format(i)) #it will remove the output file after combining

# End of Python Script

Step by Step Solution

There are 3 Steps involved in it

1 Expert Approved Answer
Step: 1 Unlock blur-text-image
Question Has Been Solved by an Expert!

Get step-by-step solutions from verified subject matter experts

Step: 2 Unlock
Step: 3 Unlock

Students Have Also Explored These Related Databases Questions!