I am a newbie in Python.
I want to know how to write a script for creating files that uses while
to create 10 files in a given path (I want the name of the first file 1.txt
and 2.txt
to 10.txt
for the rest).
Asked
Active
Viewed 114 times
-1

Dmytro Sirenko
- 5,003
- 21
- 26

user326260
- 45
- 5
-
4Welcome to StackOverflow! Please start with reading http://stackoverflow.com/help/how-to-ask . – Dmytro Sirenko May 01 '16 at 08:13
-
Why not `for`, a slightly more logical choice? – Jongware May 01 '16 at 08:14
-
Probably because it's an assignment in a programming class where the students first learn how to do a loop manually before then being taught that there is something that does the counting and condition checking `for` you... – Tim Pietzcker May 01 '16 at 08:16
-
1Then the assignment failed, `for` there is always someone who answers `while` such an assignment was designed to make the student learn something. – Jongware May 01 '16 at 08:26
-
Possible duplicate of [Creating a new file, filename contains loop variable, python](http://stackoverflow.com/questions/12560600/creating-a-new-file-filename-contains-loop-variable-python) – Tadhg McDonald-Jensen May 02 '16 at 00:16
2 Answers
1
If you insist on using while loops, a solution could look like this:
i = 1
while i <= 10:
with open("{}.txt".format(i), "w") as handle:
handle.write("Some content ...")
i += 1
However, using a for loop is much more appropriate in this case:
for i in range(1, 11):
with open("{}.txt".format(i), "w") as handle:
handle.write("Some content ...")

tobspr
- 8,200
- 5
- 33
- 46
-1
import os
def create_files(path, n):
i = 1
while i <= n:
with open(os.path.join(path, str(i) + '.txt'), 'w+') as f:
f.write('content')
i += 1
if __name__ == '__main__':
create_files('/tmp/test', 10)
use while to loop, open(path, 'w+') to create file.
I'm new to Python too, hope it helps, have fun.

Guoliang
- 885
- 2
- 12
- 20