繁体   English   中英

用单独的程序替换另一个文件中的文本

[英]Replacing Text in another file with a separate program

我有两个文件:

文字

程序.py

我将文本插入到我的

文字

使用以下行的文件:

inp=input('Text by the user')
with open("text.py", "a") as myfile:
   myfile.write(inp)

我怎样才能让程序删除文本中的行,它说:

文本 2

文本 1 文本 2

什么时候跑两次?

以写入模式 ( w ) 而不是追加模式 ( a ) 打开。 这会在写入文件之前清空文件。

inp=input('Text by the user')
with open("text.py", "w") as myfile:
   myfile.write(inp)

更少的代码

with open("text.txt", "w") as file:
    file.write(input("Write on file> "))

可重复使用的东西

def write_input(file):
    "Get and input and writes it to a file"
    inp = input("Write something: ")
    with open(file, "w") as file:
        file.write(inp)
    return inp


write_input("mytext.txt")

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM