-2

As title, Should I use open alone as this situation instead of using f=open(file) and f.close, because I don't know how to close file when I just using open.
More explain: I want to use just open instead of with-statement or f=open() and f.close() because it increase my mini app's size a few Megabytes but I don't know why, so that I just want to know if I use open alone and how it affect my app (or computer) if I could use it? (I'm just a newbie)

def resource_path(relative_path):  
  try:
      open(relative_path)
      base_path = os.path.abspath(".")
  except Exception:
      base_path = sys._MEIPASS
  return os.path.join(base_path, relative_path)
Lâm Nhân
  • 29
  • 5
  • 1
    Possible duplicate of [Does a File Object Automatically Close when its Reference Count Hits Zero?](http://stackoverflow.com/questions/1834556/does-a-file-object-automatically-close-when-its-reference-count-hits-zero) – Łukasz Rogalski Jul 11 '16 at 08:16
  • Or maybe http://stackoverflow.com/questions/7395542/is-explicitly-closing-files-important – Łukasz Rogalski Jul 11 '16 at 08:16
  • You should use `with open(path) as f:` – khelwood Jul 11 '16 at 08:21
  • 1
    If you don't use `f = open(relative_path)` you don't have a handle to the file, so you can't write or read it. Why would you open it then? – syntonym Jul 11 '16 at 08:50
  • I want to open to check out that the relative_path have file yet because I just want my app try to read relative_path file in the same location before it read the file join in exe file – Lâm Nhân Jul 11 '16 at 09:40

1 Answers1

2

Use with-statement:

def resource_path(relative_path):  
  try:
      with open(relative_path) as file:
          base_path = os.path.abspath(".")
  except Exception:
      base_path = sys._MEIPASS
  return os.path.join(base_path, relative_path)
Vlade
  • 89
  • 1
  • 7
  • Thank you! I know that this is the way to auto close file but I don't know why when I use with-statement or f=open() and f.close() my exe app build with pyinstaller --onefile increase 3Mb from 26.7 to 29.1Mb compare with just using open() – Lâm Nhân Jul 11 '16 at 09:54