0

I can't get a file to open using the open() method.

  • I wanted the file to open in notepad.
  • I feel like I was able to do this before so it is a new issue.
  • I can read the file just fine.
  • I am able to open images using PIL show() just fine.
  • Python 3.6, Windows 7.

Any help appreciated!

filename = "C:/Users/Eman-Win10/Desktop/Python_Images/test1.txt"
fo = open(filename)
print(fo.read())

C:\Users\Eman-Win10\Desktop\Python_Images>python c:/Users/Eman-Win10/Desktop/Python_Images/test2.py
These are the contents of my test1.txt file!
Eman4real
  • 538
  • 5
  • 12
  • 1
    `open()` is for opening file handles, it merely gives you a way to access the contents of a file within your program – TallChuck Jan 06 '18 at 06:28

1 Answers1

1

As @TallChuck mentioned in the comments, open() is used to create a filehandle to give you access to the file from within Python.

To make the file open in notepad from within Python, you could do:

import webbrowser

filename = "C:/Users/Eman-Win10/Desktop/Python_Images/test1.txt"
webbrowser.open(filename)

This should open the file in your default text editor.

Possibly a better way to do it would be:

import os

filename = "C:/Users/Eman-Win10/Desktop/Python_Images/test1.txt"
os.system(filename)

which under Windows should open the file using the default program for that filetype.

In a Unix environment you would have to do:

os.system('%s %s' % (os.getenv('EDITOR'), filename))
Andrew Guy
  • 9,310
  • 3
  • 28
  • 40