When I do excersise 16 and write lines to a file, U can only write to it once?!? If I run the code again opening the same file it turns up empty?!?!? :-0
Any ideas on what I might be doing wrong?!?
I open it with open(filename, ‘w’) and at the end I close it with
Basically, when you open a file using open(filename, ‘w’), you’re actually truncating the file if it already exists. And the method truncate() has the same behavior.
So I think the answer would be opening the file using open(filename, ‘a’) for appending new lines to the file. At least, I took a look on the exercise and I made some change and it worked
the open() method’s default mode is read. However, when viewing new content with print() it will not show. Try explicitly switching to read mode when opening (open, ‘r’). Then view via print(). You should then see your newly added content. Currently I don’t know why open() requires an explicit read mode. Maybe someone else can answer that.
(EDIT)
funception’s answer is also correct afaik. ‘truncate’ means to overwrite. the problem is confusion over how to view file contents.
What I’m experiencing, though, is that I write a first time to the file by running the code! I jump to terminal and type cat “filename.txt” to see content and I see it. I run the again, a second time, and there is no content in the file anymore when I do cat or use a file editor. How is that possible? :-/ One would think that the write command would over write the file everytime. Or do I have things backwards?
Like @scla said, it’s best to see your code. In fact, that’s one of the rules of the forum. You have to post your code for people to see and tell you what’s wrong. Sooooooooo many hours are wasted talking about what’s wrong with code when just the file (and sometimes a screenshot) will do it easily.
You can post your code to https://gist.github.com/ and then paste the link here. We can then go in and suggest edits to the code for you to review. Then, write out a detailed set of instructions to replicate. Like this:
Run ex16.py.
cat myfile.txt
Run ex16.py again.
cat myfile.txt.
Result: file is empty.
Expected results: file has blooblah in it.
You should also be printing out variables along the way in the script to find out what’s going on inside it. I demonstrate this a lot in the Python 3 book, but basically you do this:
print(">>> before write: text=", text)
The golden rule is print print print. Don’t just stare at it or think something magical is going on. The computer has all the data inside it’s just you don’t see any of that from the code. You have to execute it and print variables at key points to see what’s happening.