I want to create text files(empty) depending upon the user input, suppose if the user enter 20 , then it should create 1.txt,2.txt to 20.txt

Assuming i want to create 2o files, then i wrote the foll code:

for i in range(20)
   filename="i.txt"
   fp=open('filename','w')
fp.close()

but i know that there's an error in 2nd line(cannot combine interger(i) and string(.txt) while assigning it to filename, so i wanted to know any other way to cretae files in the above mentioned way.

Recommended Answers

All 6 Replies

for number in range(int(raw_input('How many? '))):          
    open("%2i.txt" % number, 'w').close()

or input if you use Python 3 produce more sensible 01txt etc number files. If you want different length names not in number order leave out the 2 length from format string.

Yes it works now.
I just started out with file handling in python, and i read that you require a file handler(eg. fp in my code) for performing file operations like opening, closing etc.
Then how did you wrote the code without any file handlers?

file handle is result of open.

file handle is result of open.

ok thanks for your response!!

Found another easier way:
just convert the integer into string .

for i in range(20)
       filename=str(i)+".txt"
       fp=open(filename,'w')
   fp.close()

You leave 19 file handles unclosed.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.