-3
i = 1
while i <=10:

    f = open("txtfile.txt",+str(i) "a+")

    f.write("111\n")
    f.write("222\n")
    i = i + 1
    f.close()

I want to create txt in many times , But the top code is not in my mind.

I want to create a txt.file1 , and if it exist , the next time execute name is txt.file2.

mrEvgenX
  • 758
  • 8
  • 16
Lu儒
  • 3
  • 4

2 Answers2

0

Here is a simple way to create 10 files in Python 3.6+, named from file.txt01 to file.txt10:

from pathlib import Path

for i in range(1, 11):
    f = Path(f'file.txt{i:02d}')
    f.write_text('111\n222\n')

If you want to create a new file on every run, sequentially numbered ad infinitum, do this:

from pathlib import Path

i = 1

while True:
    if Path(f'file.txt{i}').exists():
        i += 1
    else:
        Path(f'file.txt{i}').write_text('111\n222\n')
        break

But that is very inefficient though.

So maybe this is a better solution:

from pathlib import Path

source = Path('/home/accdias/temp')
prefix = 'file.txt'
slots = set([int(_.name.replace(prefix, '')) for _ in source.glob(f'{prefix}*')])
slot = min(set(range(1, max(slots, default=1) + 1)) - slots, default=max(slots, default=1) + 1)
filename = source / f'{prefix}{slot}'
filename.write_text('111\n222\n')

The solution above is nice because it take into account any gaps that may exist and pick the next lowest slot number available.

accdias
  • 5,160
  • 3
  • 19
  • 31
  • nah, he want to create one file for each time execute, and preventing name to be same, not creating 10 at the time. – okie Dec 27 '19 at 10:03
  • @WhereisourMonica, the code posted doesn't show that. The `while` loop shows the contrary. But the question is not clear anyway. He needs to clarify it. – accdias Dec 27 '19 at 10:04
0

Assuming, on every run new file (txtfileNN.txt) with incremented number need to be created ( NN is one or two digit number), try below code:

import os
import re

file_base_name = 'txtfile'
r = re.compile(file_base_name+'\d{0,2}.txt')
all_files_in_dir=sorted([i for i in os.listdir() if r.match(i)])
print('Existing files in directory: {}'.format(all_files_in_dir))
# Existing files in directory: ['txtfile.txt', 'txtfile1.txt', 'txtfile10.txt']

if not all_files_in_dir:
    # File does not exist yet
    out_file = file_base_name + '.txt'
else:
    highest_file=all_files_in_dir[-1]
    # 'txtfile10.txt'
    int_portion = highest_file.replace('.txt', '').split(file_base_name)[-1]
    if not int_portion:
        # no integer in file, so it it txtfile.txt
        next_int = 1
    else:
        next_int = int(int_portion) + 1

    out_file = file_base_name + str(next_int) + '.txt'
print('Next file name : {}'.format(out_file))
# Next file name : txtfile11.txt

# Now write text in new file    
f = open(out_file, 'a')
f.write("111\n")
f.write("222\n")
f.close()
  • How can I use this code to create over txtfile10.txt ? @Nasimuddin Ansari – Lu儒 Dec 30 '19 at 03:03
  • @Lu儒 I did not get your question. Please elaborate it. – Nasimuddin Ansari Dec 30 '19 at 07:01
  • Your code can create txtfile2 , when txtfile1 exists, but it only can create until txtfile10 , if I want create txtfile11 , Is it possible? Thanks!! @Nasimuddin Ansari – Lu儒 Dec 30 '19 at 07:37
  • if txtfile11 is highest numbered file, it will create txtfile12. if txtfile14 is highest numbered file, next file will be txtfile15 and so on ... please tweak code as per your need – Nasimuddin Ansari Dec 30 '19 at 07:52
  • Hi I can create over 10 txtfile , but can you tell me your code in line '\d{0,2} diffenent in '\d{2} when I use '\d{2} , I can create over txtfile10. Thanks @Nasimuddin Ansari – Lu儒 Dec 30 '19 at 08:07
  • ```\d{0,2}``` regex means - number of digits may from 0 or 1 or max 2. ```\d{2}``` regex means - always 2 digit (10 to 99) – Nasimuddin Ansari Dec 31 '19 at 01:26
  • Thank you very much. I wonder why {0,3} can't create txtfile0~txtfile100. When I want to create txtfile0~txtfile100 it need to use {0,2} then I can use {3} to create txtfile10~txtfile100. @Nasimuddin Ansari – Lu儒 Dec 31 '19 at 08:04