0

I have files in a directory, named as hosts_access_log_00.txt, hosts_access_log_01.txt and so on till 13. And the output for the respective files must be stored in the respective files : bytes_hosts_access_log_00.txt, bytes_hosts_access_log_01.txt and so on till 13 and they should be stored in the current directory. How do I achieve this ? In the above code I am only able to achieve this with 1 file.

with open('hosts_access_log_00.txt', 'r') as input_file:
    bytes = []
    for lines in input_file.readlines():
        words = lines.split()
        bytes.append(words[-1])

bytes = list(int(byte) for byte in bytes)
usable_bytes = []
sum = 0
for usable in bytes:
    if usable > 5000:
        usable_bytes.append(usable)
        sum += usable

print(usable_bytes, sum)
bytecount = '{}'.format(len(usable_bytes))
sum_state = '{}'.format(sum)

with open('bytes_hosts_access_log_00.txt', 'w') as output_file:
    output_file.write(bytecount +'\n'+ sum_state)
HElloWold
  • 9
  • 1

1 Answers1

0

You have 14 files and they are named consecutively, right? I would use a simple loop and f-strings.

for filenumber in range(14):
    filenumber = str(filenumber)
    filenumber = '0' * (2 - len(filenumber)) + filenumber
    with open(f'hosts_access_log_{filenumber}.txt', 'r') as input_file:
        bytes = []
        for lines in input_file.readlines():
            words = lines.split()
            bytes.append(words[-1])

    bytes = list(int(byte) for byte in bytes)
    usable_bytes = []
    sum = 0
    for usable in bytes:
        if usable > 5000:
            usable_bytes.append(usable)
            sum += usable

    print(usable_bytes, sum)
    bytecount = '{}'.format(len(usable_bytes))
    sum_state = '{}'.format(sum)

    with open(f'bytes_hosts_access_log_{filenumber}.txt', 'w') as output_file:
        output_file.write(bytecount +'\n'+ sum_state)
MattDMo
  • 100,794
  • 21
  • 241
  • 231
Kate Melnykova
  • 1,863
  • 1
  • 5
  • 17