I am pretty new to Python, and currently working on a script to help me automate the task of creating multiple files with a similar file-name structure and I couldn't seem to get it working.
I would like to create a function that takes in a user input(), for example, the letter "T" and how many "T" would user like to make, and it automatically creates a bundle of files with the format as follows:
- T1_S1.txt
- T1_S2.txt
- T1_S3.txt
- T1_S4.txt
- T2_S1.txt
- T2_S2.txt
- T2_S3.txt
- T2_S4.txt
- .....
So for each "T", there should be four "S" before the increment of the "T" part adds a new increment number.
I would really appreciate it if someone could help with this.
CodePudding user response:
You can use a little bit of arithmetics and write:
def fileCreator(num):
for i in range(num):
open(f"T{1 i // 4}_S{1 i % 4}.txt", "w")
The only argument is the number of files you want to create.
CodePudding user response:
If you are on a unix system mac/linux then you can simply do this
touch T{1..2}_S{1..4}.txt
CodePudding user response:
Here is a very simple answer and you can customize it too.
def CreateFile(filerange, filename, extension_name, extension_length):
for i in range(0, filerange):
for j in range(0, extension_length):
f = open(f"{filename}{i 1}_{extension_name}{j 1}.txt", "a")
f.write("You can add here your text or customize as per your needs")
f.close()
CreateFile(2, 'T', 'S', 4)
Hope This help you:
filerange -> no of files you need eg:2 files T1,T2
filename -> Should be your filename eg:T
extension_name -> eg:S
extension_length -> eg:S1,S2,S3,S4
Here is the output:
T1_S1.txt
T1_S2.txt
T1_S3.txt
T1_S4.txt
T2_S1.txt
T2_S2.txt
T2_S3.txt
T2_S4.txt
CodePudding user response:
You can easily create files using the built-in with function, and you can loop through a function that would create a variety of files with names. Something like this: