fout.write()之后.txt文件末尾的奇怪加法-Python

时间:2018-08-03 09:06:15

标签: 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)

预先感谢

2 个答案:

答案 0 :(得分:0)

您的替换字符串比原始模板的占位符短,导致在执行文件查找后出现剩余字符。您应该在调用seek()之前截断文件,以便可以修剪末尾的多余字符。

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

答案 1 :(得分:0)

您正在同时以不同的方式打开同一文件(out.txt)-这难道不是您的罪恶吗? 这就像有3个人在同一个锅里做饭。一个做鸡蛋,一个培根,第三个焦糖:可能会起作用-不想尝尝。

更清洁的代码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