所以我刚刚创建了一个文本文件,并使用 with 循环从一个已经存在的文件中复制了文本。如何在同一个程序中打开新创建的文件?

So I just created a text file and copied text from an already existing file using a with loop. How do I open newly created file in same prog?

我正在制作一个从输入文件中获取文本的程序,然后您输入一个文件,它会在其中复制已经存在的文件文本。然后,我需要在那里替换几个词并打印这些词被替换的数量。到目前为止,这是我的代码,但是由于 with 循环关闭了新创建的文件,我不知道如何再次打开它进行读写和计数。到目前为止,这是我糟糕的代码:

filename=input("Sisesta tekstifaili nimi: ")
inputFile=open(filename, "r")
b=input("Sisesta uue tekstifaili nimi: ")
uusFail=open(b+".txt", "w+")
f=uusFail
with inputFile as input:
    with uusFail as output:
        for line in input:
            output.write(line)

lines[]
asendus = {'hello':'tere', 'Hello':'Tere'}
with uusFail as infile
    for line in infile
        for src, target in asendus
            line = line, replace(src, target)
        lines.append(line)
    with uusFail as outfile:
        for line in lines:
            outfile.write(line)

您需要在第二个代码块中重新打开文件:

with open(b+".txt", "r") as infile:

您的代码中有很多不必要的循环。当你读取文件时,你可以把它当作一个整体,统计出现的次数并替换它们。这是您的代码的修改版本:

infile = input('Enter file name: ')
outfile = input('enter out file: ')
with open(infile) as f:
  content = f.read()
asendus = {'hello':'tere', 'Hello':'Tere'}
my_count = 0
for src, target in asendus.items():
  my_count += content.count(src)
  content = content.replace(src, target)


with open(f'{outfile}.txt','w+' ) as f:
  f.write(content)