我正在尝试使用popen打开记事本并将一些内容写入其中。我无法解决这个问题。我可以使用以下命令打开记事本:

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

我正在尝试确定如何使用python在文本文件中写入任何内容。任何帮助表示赞赏。

最佳答案

您可能将(文本)文件的概念与操纵它们的过程相混淆。

记事本是一个程序,您可以创建一个过程。另一方面,文件只是硬盘驱动器上的结构。

从编程的角度来看,记事本不会编辑文件。它:


将文件读入计算机内存
修改该内存的内容
将内存写回到文件中(可以用类似的名称命名,也可以用其他名称-被称为“另存为”操作)。


您的程序与其他程序一样,可以像记事本一样操作文件。特别是,您可以执行与记事本完全相同的序列:

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

关于python - 记事本的Python子进程,我们在Stack Overflow上找到一个类似的问题:https://stackoverflow.com/questions/28853923/

10-11 22:16
查看更多