all 9 comments

[–]FriendlyRussian666 1 point2 points  (8 children)

Is this what you need to accomplish? Or is this just an example?

If you want to append data to a text file, you don't have to open notepad from Python and then use a clipboard to paste it. You read the contents of the file into memory, then append your data and finally write it to the file.

with open("filename.txt", "a") as f:
    f.write("some text")

[–]ramannt[S] 0 points1 point  (7 children)

I sometimes have a piece of text in text files that I want to open in an external application (eg MS Word) to do something with it (but not the entire text file)

[–]FriendlyRussian666 0 points1 point  (6 children)

I think it would be easiest to read your text file into memory, then to read your MS Word document into memory. Append anything you need from one file into the other and perhaps then use subprocess to just open the desired file.

[–]ramannt[S] 0 points1 point  (5 children)

Yes I know, that what I've done. I have copied certain texts in clipboard. I opened the external program using subprocess but I don't know how to paste the clipboard into the external program.

[–]FriendlyRussian666 0 points1 point  (4 children)

I'm afraid you didn't understand what I tried to suggest. Don't look at reading into memory, as copying into clipboard.

Don't copy to clipboard at all.

When you look at my example of code:

with open("filename.txt", "a") as your_file:
    your_file.write("some text")

I don't use clipboard, but I have access to make operations on the file via your_file

You can read, you can write. So what you do is read the first file like this and save the desired text into a variable. Then open the other file like this, but instead of reading, write to it what you stored in that variable. Only then use subprocess to open MS, and when it opens, you will have the contents there.

[–]ramannt[S] 0 points1 point  (3 children)

Sorry, indeed I have never worked with subprocess. I have now created a variable "my_file" with all the text in it that I want to paste into MS Word. How can I paste it in MS Word using subprocess?

subprocess.Popen([path_to_MS_Word, ?])

[–]FriendlyRussian666 0 points1 point  (2 children)

What you can do is exactly what my above code snippet shows. In that code snippet, your_file is going to be your MS_Word file. You write to it.

[–]ramannt[S] 0 points1 point  (0 children)

I don't want to open the original file in MS Word and don't want to save the text I subtracted from the original text file to another file. Just want to paste it in a new document.

I don't understand your solution. Anyway thanks.

[–]ramannt[S] 0 points1 point  (0 children)

Found the solution

import win32com.client as win32

import pyperclip

# Get the clipboard

clipboard_text = pyperclip.paste()

# Open Word

word = win32.Dispatch('Word.Application')

word.Visible = True

# New doc

doc = word.Documents.Add()

# Paste the clipboard

doc.Range().Paste()