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.

7
  • Why can't you write to a file directely? Commented Mar 4, 2015 at 12:02
  • I am trying to Automate it :) Commented Mar 4, 2015 at 12:03
  • You don't have to open notepad. You can write to a file from python. Commented Mar 4, 2015 at 12:04
  • 3
    code.google.com/p/pywinauto (UIAutomation) Commented Mar 4, 2015 at 12:04
  • 2
    related: Interact with other programs using Python Commented Mar 4, 2015 at 12:11

3 Answers 3

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")
Sign up to request clarification or add additional context in comments.

3 Comments

I can do this, but I am trying to open a notepad with some text (using python) in it.
@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?
@J.F.Sebastian I can do this, but I found more efficient way by using pywinauto.
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

1 Comment

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..
0

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

1 Comment

Consider what is said in @Matteo Italia's comment. It may also apply in your case.

Your Answer

By clicking “Post Your Answer”, you agree to our terms of service and acknowledge you have read our privacy policy.

Start asking to get answers

Find the answer to your question by asking.

Ask question

Explore related questions

See similar questions with these tags.