如何在其他执行中创建不同的 txt.name


i = 1
while i <=10:
f = open("txtfile.txt",+str(i) "a+")
f.write("111n")
f.write("222n")
i = i + 1
f.close()

多次想创建txt,但顶层代码并不在我的脑海中。

我想创建一个 txt.file1,如果它存在,下次执行名称是 txt.file2。

假设在每次运行时都需要创建具有递增数字的新文件(txtfileNN.txt((NN是一位或两位数字(,请尝试以下代码:

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("111n")
f.write("222n")
f.close()

这是一个在 Python 3.6+ 中创建 10 个文件的简单方法,从file.txt01file.txt10命名:

from pathlib import Path
for i in range(1, 11):
f = Path(f'file.txt{i:02d}')
f.write_text('111n222n')

如果要在每次运行时创建一个新文件(按顺序编号无限(,请执行以下操作:

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('111n222n')
break

但这效率很低。

所以也许这是一个更好的解决方案:

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('111n222n')

上面的解决方案很好,因为它考虑了可能存在的任何间隙并选择下一个可用的最低插槽号。

相关内容

最新更新