-2

I wrote a program to open a file and print every single line if the file is not there create it and write some line to it

it works perfectly when the file is not present in the directory but when the file is there it opens the file reading it -->and then writing it to the file but it should only read the file

print("We will do some file operation")
filename=input("enter a file name: ")
try:
 file=open(filename,'r')
 print("File opened")
 for line in file:
    print(line )
 filename.close()
 print("file cosed")

except:
 file=open(filename,'w')
 print("File created")
 for i in range(15):
    file.write("This is line %d\r\n"%(i))
 print("write operation done")
 file.close()
Geofe Geo
  • 15
  • 3

1 Answers1

0

In the try block of your code, you set file=open(filename,'r'). However at the end of the block, you attempt filename.close(). You want to close the file, not the input string.

try:
    file=open(filename,'r')
    print("File opened")
    for line in file:
        print(line )
    file.close()             #wrong variable name on this line
    print("file cosed")

Your indentation is also wrong in the question you posted, it should look as above. Blanket exceptions are also not ideal, you should use:

except IOError:
Trelzevir
  • 767
  • 6
  • 11