所以我刚刚创建了一个文本文件并使用 with 循环从现有文件中复制了文本。如何在同一个 prog 中打开新创建的文件?

Posted

技术标签:

【中文标题】所以我刚刚创建了一个文本文件并使用 with 循环从现有文件中复制了文本。如何在同一个 prog 中打开新创建的文件?【英文标题】: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? 【发布时间】:2021-11-04 16:46:50 【问题描述】:

我正在制作一个从输入文件中获取文本的程序,然后你输入一个文件,它会在其中复制现有的文件文本。然后,我需要在那里替换几个单词并打印这些单词中被替换的数量。到目前为止这是我的代码,但是由于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)

【问题讨论】:

您好,欢迎来到 SO。您真的不想使用input 作为变量名。如果你想要一些简单的东西,我倾向于使用file_in 为什么不在for line in input: 循环中进行计数和替换? with 语句本身并不是“循环”。他们可能会包装一个。 【参考方案1】:

您的代码中有很多不必要的循环。当您阅读文件时,您可以将其视为一个整体并计算出现次数并替换它们。这是您的代码的修改版本:

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)

【讨论】:

为什么最后又加了一个outfile?我希望替换发生在您创建的第一个 outfile 中。你创建了另一个额外的文件 @RCWZX 在这种情况下,您只需要删除 2 即可。但是,如果您想直接覆盖,为什么要写入文件? 我希望它从 infile 中进行替换,然后将其复制到一个 outfile 中。 @RCWZX 在这种情况下,您只需要第二个 with 语句。我已经用更改更新了代码。无论如何,您需要做的是直接处理内容,然后仅在需要时保存。 非常感谢,我会分析代码以确保我能理解所有内容;)【参考方案2】:

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

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

【讨论】:

以上是关于所以我刚刚创建了一个文本文件并使用 with 循环从现有文件中复制了文本。如何在同一个 prog 中打开新创建的文件?的主要内容,如果未能解决你的问题,请参考以下文章

循环遍历 Excel 工作表并使用 C# 将文本保存到 TXT 文件中

打印到文本文件[重复]

如何一次读取并附加到文本文件?

如何让python循环写入文档的内容不被后面写入的内容覆盖

Qt with OpenCV:程序意外完成

如何在单击href时翻转展开或折叠文本 - 淘汰赛