Follow

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use
Contact

Is it important to specify file mode('w', 'r', 'a') when opening a file? What happens when you don't?

Hi I’m a beginner programmer and I recently started writing some code. I found out that when opening files, you can specify the file mode or the operation you want to do with the file.

For example: with open(file.txt, 'r') as file:

I tried experimenting and found out that if I just do with open(file.txt) as file: I can still do the things I want to do with the file which is read its contents into memory.

MEDevel.com: Open-source for Healthcare and Education

Collecting and validating open-source software for healthcare, education, enterprise, development, medical imaging, medical records, and digital pathology.

Visit Medevel

My question then are:

  1. Is it really important to specify the file mode when accessing/opening it?
  2. Is it bad if I don’t specify?
  3. Does not specifying only work with python?

Thanks in advance

>Solution :

Hi @Mendrezzzzz it’s nice that you starting programming

  1. No if you just want to read it it is not needed, because "r" is default, but it makes it more readable, so that if you or someone else later is reading your Code immediately knows which mode this file is opened

  2. For Readability in my opinion yes. But it doesn’t break your Code so practically no. But please consider the readability for the future you or person who is reading your code

  3. Well this is tricky there are many languages, where you have to give a Mode for a Filestream or where you have to Use completely different Classes for the different Modes (Java), but there sure are other languages like python making Reading the default mode (I don’t know every language)

I hope this helps you. I would recommend to learn also Coding Conventions if you want really to learn programming.

Good Python tutorial https://automatetheboringstuff.com/2e/chapter1/

Add a comment

Leave a Reply

Keep Up to Date with the Most Important News

By pressing the Subscribe button, you confirm that you have read and are agreeing to our Privacy Policy and Terms of Use

Discover more from Dev solutions

Subscribe now to keep reading and get access to the full archive.

Continue reading