-1

I'm playing around with try: and am expecting 'Hello' to be written to testfile.tx. However when I check the file, 'Hello' doesn't appear. What is wrong with my code?

try: f = open('testfile.txt', 'w') f.write('Hello') except TypeError: print ('There was a type error') except OSError: print('There was an OS error') finally: print('I always run') 
9
  • 2
    Works for me. Do you get any errors? Are you sure you're checking the right output file? Commented Mar 1, 2024 at 20:06
  • 2
    Use finally: f.close() Commented Mar 1, 2024 at 20:08
  • 4
    Maybe use with open(...) altogether. Commented Mar 1, 2024 at 20:08
  • 2
    The file will be created in the current directory. It sounds like you're just looking in the wrong directory for the file (and the directory where you're looking might also have an empty file of the same name). You can add this code to see the actual current directory import os; print(os.getcwd()) Commented Mar 1, 2024 at 20:10
  • 2
    @JorgeGandara, I understand that you're frustrated. But there are good reasons for rate limiting and other restrictions on question asking. Changing an old question is counterproductive for many reasons, not least of which that you aren't likely to get answers to the new question that way. In any case, profanity is not appropriate. Please read our code of conduct. Commented Mar 15, 2024 at 18:18

2 Answers 2

2

I see you already fixed the problem by doing this:

try: f = open('testfile.txt', 'w') f.write('Hello') except TypeError: print ('There was a type error') except OSError: print('There was an OS error') finally: f.close() print('I always run') 

This is alright, and properly writes the data in the buffer. However, you're better off using a context manager.

This syntax is more concise, less mistake-prone, and automatically closes the file even if an error occurs:

with open('testfile.txt', 'w') as f: f.write("Hello") 
Sign up to request clarification or add additional context in comments.

2 Comments

I agree, - I just wanted to be as consistent with what the poster had in their code as possible
Got it, I'll change the code
0

I didn't close the file with f.close()

I added f.close() and it works now!

Thanks for everyone's help!

1 Comment

Oh, so you were running this code inside of an IDE or shell, not as a separate script? Mentioning that would have been helpful.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.