For example, I created a directory and want to populate it with a specified number of files. For example
File 1
File 2
File 3
etc . . .
File n
all in the same directory.
For example, I created a directory and want to populate it with a specified number of files. For example
File 1
File 2
File 3
etc . . .
File n
all in the same directory.
If you're running Python 3.4+ you can do it easily with pathlib
:
from pathlib import Path
n = 9
for i in range(1, n+1):
Path(f"File{i}").touch()
Python2/3 compliant, using os.system
.
import os
for i in range(5):
os.system('touch File%d' %i)
An alternative approach using subprocess
, as suggested by idjaw:
import subprocess
for i in range(5):
subprocess.Popen(['touch', 'File{}'.format(i)])
for i in range(5):
os.system('type nul > File%d' %i)
for i in range(5):
with open('File%d' %i, 'w') as f: pass
Without pathlib
, and cross-platform:
import os
target_path = "/path/to/target/dir"
files_num = 9
for i in range(files_num):
with open(os.path.join(target_path, "File{}".format(i+1)), "a"):
pass