0

I am using open function to write a text file

I am using IDLE for code execution

File = open('abcd.txt','w')
for i in range(10):
    File.write("this is line %d\n" % (i+1))
    File.close()

my Expected result is

this is line 1
this is line 2
this is line 3
'''''
'''''
this is line 10

1 Answers1

1

You File.close() in the first iteration. Any subsequent File.write calls will fail because File is already closed.

Use with:

with open('abcd.txt','w') as File:
    for i in range(10):
        File.write("this is line %d\n" % (i+1))
DeepSpace
  • 78,697
  • 11
  • 109
  • 154