简体   繁体   English

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

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

I have two files:我有两个文件:

text文字

and

program.py程序.py

I insert text into my我将文本插入到我的

text文字

file using the line:使用以下行的文件:

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

How can i make the program delete the line in text having it say:我怎样才能让程序删除文本中的行,它说:

text2文本 2

not

text1 text2文本 1 文本 2

when run two times?什么时候跑两次?

Open in write mode ( w ) instead of append mode ( a ).以写入模式 ( w ) 而不是追加模式 ( a ) 打开。 This blanks the file before writing to it.这会在写入文件之前清空文件。

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

Less code更少的代码

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

Something reusable可重复使用的东西

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