3

I am trying to open Notepad using popen and write something into it. I can't get my head around it. I can open Notepad using command:

notepadprocess=subprocess.Popen('notepad.exe')

I am trying to identify how can I write anything in the text file using python. Any help is appreciated.

hyades
  • 3,110
  • 1
  • 17
  • 36
Bash Noob
  • 53
  • 2
  • 10

3 Answers3

2

You can at first write something into txt file (ex. foo.txt) and then open it with notepad:

import os

f = open('foo.txt','w')
f.write('Hello world!')
f.close()
os.system("notepad.exe foo.txt")
Timur Osadchiy
  • 5,699
  • 2
  • 26
  • 28
  • I can do this, but I am trying to open a notepad with some text (using python) in it. – Bash Noob Mar 04 '15 at 12:05
  • @BashNoob: what happens if you run Tim Osadchiy's code? I expect that it opens notepad with `Hello world!` text in it. What do you see? – jfs Mar 04 '15 at 12:12
  • @J.F.Sebastian I can do this, but I found more efficient way by using pywinauto. – Bash Noob Mar 04 '15 at 12:34
2

You may be confusing the concept of (text) file with the processes that manipulate them.

Notepad is a program, of which you can create a process. A file, on the other hand, is just a structure on your hard drive.

From a programming standpoint, Notepad doesn't edit files. It:

  • reads a file into computer memory
  • modifies the content of that memory
  • writes that memory back into a file (which could be similarly named, or otherwise - which is known as the "Save as" operation).

Your program, just as any other program, can manipulate files, just as notepad does. In particular, you can perform exactly the same sequence as Notepad:

my_file= "myfile.txt"        #the name/path of the file
with open(file, "rb") as f:  #open the file for reading
    content= f.read()        #read the file into memory
content+= "mytext"           #change the memory
with open(file, "wb") as f:  #open the file for writing
    f.write( content )       #write the memory into the file
loopbackbee
  • 21,962
  • 10
  • 62
  • 97
  • Thanks for clarifying. I am trying to to the third part. So This is what I am trying to do - open notepad and write something into it, just like opening cmd prompt and sending commands using popen.communicate.. – Bash Noob Mar 04 '15 at 12:11
0

Found the exact solution from Alex K's comment. I used pywinauto to perform this task.

Bash Noob
  • 53
  • 2
  • 10
  • Consider what is said in [@Matteo Italia's comment](http://stackoverflow.com/a/14338006/4279). It may also apply in your case. – jfs Mar 04 '15 at 12:43