Home > Blockchain >  Python - Passing a number as a parameter to filename
Python - Passing a number as a parameter to filename

Time:12-22

for example i have two files .txt. First file has 78 lines, second file has 30 lines. Is there any easy way to pass a number as a parameter to the result? Currently in result I get:

first_file_20.txt
first_file_40.txt
first_file_60.txt
first_file_80.txt
second_file_20.txt
second_file_40.txt

but I would like to have as a result:

first_file_1.txt
first_file_2.txt
first_file_3.txt
first_file_4.txt
second_file_1.txt
second_file_2.txt

code:

import re
import os

lines_per_file = 20
smallfile = None

root_path = os.getcwd()

if os.path.exists(root_path):
    files = []
    for name in os.listdir(root_path):
        if os.path.isfile(os.path.join(root_path,name)):
            files.append(os.path.join(root_path,name))
    print(files) #list all files in directory

    for ii in files:
        if ii.endswith(".txt"): # only txt files
            with open(ii,'r') as bigfile:
                name1 = str(os.path.basename(ii).split(".")[0])
                name2 = str(name1   '_{}.txt')
                #
                print('name', name2)
                for lineno, line in enumerate(bigfile):
                    w = 1
                    if lineno % lines_per_file == 0:
                        if smallfile:
                            smallfile.close()
                        small_filename = name2.format(lineno   lines_per_file)
                        smallfile = open(small_filename, "w")
                    smallfile.write(line)
                if smallfile:
                    smallfile.close()

Anyone can help me?

CodePudding user response:

Don't add lineno and lines_per_file, divide them.

small_filename = name2.format(lineno//lines_per_file   1)
  • Related