在.txt文件末尾添加奇怪的内容fout.写入()Python

2024-07-03 07:02:28 发布

您现在位置:Python中文网/ 问答频道 /正文

我正在写一个程序,可以从模板中提取变量,并有效地查找/替换到模板中。你知道吗

模板示例:

VARIABLES

@username
@password
@secret

###########################################################

My username is @username
Password is @password
Secret is @secret

程序将找到每个变量并逐个请求用户输入,打开文件,保存内容,然后关闭文件,为下一个变量做好准备。你知道吗

除了一个奇怪的以外,一切正常。一旦我运行了代码,我的文本文件的结尾似乎有点疯狂。参见下面的输出。正如您所见,它成功地获取并放置了变量,但是它在末尾添加了“TESTis TESTetis@secret”?你知道吗

VARIABLES

User
Pass
TEST

###########################################################

My username is User
Password is Pass
Secret is TESTis TESTis TESTetis @secret

我是Python新手(本周),请原谅下面的代码。我用自己独特的方式让它工作!它可能不是最有效的。只是努力想知道额外的钱是怎么加上去的。你知道吗

代码:

##COPY CONTENTS FROM READ ONLY TO NEW FILE
with open("TestTemplate.txt", "rt") as fin:
    with open("out.txt", "wt") as fout:
        for line in fin:
            fout.write(line)
        fin.seek(0)
        fout.seek(0)
        fin.close()
        fout.close()

##PULL VARIABLES AND FIND/REPLACE CONTENTS
with open("out.txt", "rt") as fin:
    with open("out.txt", "rt") as searchf:
        with open("out.txt", "r+") as fout:
            for line in fin:
                if line.startswith("@"):
                    trimmedLine = line.rstrip()
                    ## USER ENTRY
                    entry = input("Please Enter " + trimmedLine + ": ")
                    for line in searchf:
                        ## ENSURE ONLY VARIABLES AFTER '#' ARE EDITED. KEEPS IT NEAT
                        if trimmedLine in line:
                            fout.write(line.replace(trimmedLine,entry))
                        else:
                            fout.write(line)
                    ##RESET FOCUS TO THE TOP OF THE FILE READY FOR NEXT ITERATION
                    searchf.seek(0)
                    fout.seek(0)

提前谢谢


Tags: intxtsecretisaswithlineusername
2条回答

您正在打开同一个文件(顺序文件)同时以不同的方式-你不觉得这是邪恶的吗?就像三个人在同一个锅里做饭一样。一个做鸡蛋,一个熏肉,第三个焦糖:可能会解决-我不喜欢尝它。

清洁剂代码IPO-Model (yeah its old, but still valid)

  • 打开文件,读入内容,关闭文件。你知道吗
  • 做你的替代品。你知道吗
  • 打开输出文件,写入替换的文本,关闭文件。你知道吗

读取文件的较短版本:

with open("TestTemplate.txt", "rt") as fin,
     open("out.txt", "wt") as fout:
        text = fin.read() # read in text from template

        fout.write(text)  # you could simply use module os and copy() the file ...
                          # or simply skip copying here and use open("out.txt","w") below

使用此处的固定文本-您可以按上述方式获取:

text = """VARIABLES

@username
@password
@secret

###########################################################

My username is @username
Password is @password
Secret is @secret"""        

replaceMe = {} # dictionary to hold the to be replaced parts and its replacement

# go through all lines
for l in text.splitlines():
    if l.startswith("@"): # if it starts with @, ask for content top replace it with
        replaceMe[l.rstrip()] = input("Please Enter {}:".format(l.rstrip()))

newtext = text
# loop over all keys in dict, replace key in text
for k in replaceMe:
    newtext = newtext.replace(k,replaceMe[k])

print(text)
print(newtext)

# save changes - using "w" so you can skip copying the file further up
with open("out.txt","w") as f:
    f.write(text)

更换后输出:

VARIABLES

a
b
c

###########################################################

My username is a
Password is b
Secret is c

替换字符串比原始模板的占位符短,因此在执行文件查找后会产生剩余字符。您应该在调用seek()之前截断文件,以便可以修剪结尾处的多余字符。你知道吗

##RESET FOCUS TO THE TOP OF THE FILE READY FOR NEXT ITERATION
searchf.seek(0)
fout.truncate()
fout.seek(0)

相关问题 更多 >