Home > Blockchain >  Is it important to specify file mode('w', 'r', 'a') when opening a fil
Is it important to specify file mode('w', 'r', 'a') when opening a fil

Time:07-29

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.

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

CodePudding user response:

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/

  • Related