0

I am trying to get my program to write over a simple config.txt file. Which is actually working: it writes the new content over the old one if one condition is met and proceeds to the next block. However, when the next block calls another function of my program, the content of the file simply dissapears: the .txt file becomes empty.

I have searched SO for similar issues but couldn't find any posts. I looked into: How to search and replace text in a file using Python? Search and replace a line in a file in Python And and got some of these to work but always ran into the issue above.

Please be gentle as I am a newbie and this is my first "not Hello_world" program and my first post. Thanks:)

>>>Content of the default config.txt file is 'runcount=0'

    def alias(confirmation):

        ###First block###
        if confirmation.lower()=='yes':
            print("...")

            config=open('config.txt','r')
            data=config.read()
            config.close()

            newdata=data.replace('runcount=0','runcount=1')

            config=open('config.txt','w')
            config.write(newdata)
            config.close()

            confirmation2=input()

>>>Content of the config.txt file is now 'runcount=1'

            ###Second block###
            if confirmation2.lower()=='yes':
                print("...")
                return main()
            else:
                ...

>>>The main() function is called... However the config.txt file is now empty

I choose to show you this code because I think it is the most readable. I tried the "with" method which gives me the same results. I also tried to write to a new file, remove the default and rename the new to config.txt... same issue. I don't get why the file becomes empty as I closed it. No error msg, my program just goes on but the file is empty. Please note that I used open(config.txt, 'r') in another function of my program, only once yet.

Nlyo
  • 1
  • 1
  • 1
    It doesn't look to me like anything is wrong. It seems like `main()` must be doing something that clobbers the contents of `config.txt`. What happens if you replace the call to `main()` with something else, like `print("Would call main() here")`? – Ken Williams May 23 '19 at 19:16
  • You are sure about not opening the file with write mode ('w') again, right? – MeteHan May 23 '19 at 19:20
  • Oh well, I did a search and it happens that I started coding with open(config.txt) in main() and did not finish it a few hours ago... That's kid of dumb. But you ended hours of suffering.. Thank you. – Nlyo May 23 '19 at 19:24

1 Answers1

0

It happens that I coded the following line in main() and did not close config.txt:

config=open("config.txt","w+")

And forgot about it... Thank you guys for the hint. I'm going to hide somewhere very dark now.

Nlyo
  • 1
  • 1