2

I am trying to write a program that will create files, one file should look like this:

1

19

next file

2

18

3

17

etc...

and so until the 19 is on the first line and 1 is on the second line, pretty much i am incrementing firs line from 1 to 19 and decrementing second line from 19 to 1. I have this code which creates the file and writes the first number but not the last, any suggestions please?

 for x in range(1,19):
       file = open("test%x"%x, 'w')
       file.write('%x'%x)
       for x in range(19,1):
           file = open("test%x"%x, 'a')
           file.write('%x'%x)
       file.close()
0

4 Answers 4

2

You could try something like this:

for x in range(1,20):
   f = open("test"+str(x), 'w')
   f.write(str(x) + "\n" + str(20-x))
   f.close()
Sign up to request clarification or add additional context in comments.

Comments

2

Something like this should work:

num = 19
for x in range(1, num+1):
    with open file(''.join(['file_',
                            str(x),
                            '.txt'], 'w') as the_file:
        file.write(''.join([str(x),
                            '\n',
                            str(num-x+1)])

Comments

0

You're using two files with the same fileObject name without ever closing the first one. That's an issue. Why re-open it at all? If you want to make 19 files just write what you need, close it, and move on.

Secondly, remember that the second argument in the range() function is the upper bound/limit. It is a value that range will grow to meet, but never actually achieve. So if you want 1-19, your range needs to be 1-20.

 num = 19
 for x in range(1,20):
       filename = "test%d.txt" % (x)
       writeFile = open(filename, 'w')
       writeFile.write("%d" % (num))
       writeFile.close()
       num -= 1

Comments

0

if u want to make a text file may use this

for x in range(1,51):
    text = open(r"file path"+str(x)+".txt", 'w')
    text.write(str(x) + "\n" + str(51-x))
    text.close()

Comments

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.