如何在 python 中复制文本文件

How to copy text file in python

这是我想要做的:

import copy
def printtext(swefile):
    for row in swefile:
        print(row)
text = open("wordsv.txt","r",encoding="utf-8")
text2 = copy.copy(text)
printtext(text)
print(text2.readlines())

但这是不可能的,类型错误:无法序列化“_io.TextIOWrapper”对象。 所以我想知道是否有 "cloning" 文本变量的好方法,以便我可以再次打印所有行。我知道我可以再读一遍这个文件,但这个答案并不能解决我遇到的更大的问题,所以任何关于如何完成这个的建议都是有帮助的。


这是更大的上下文,因为我无法根据您的建议解决我的问题:

with open(textfilename, "r", encoding = "utf-8") as swefile:
    for row in swefile:
        word = row.strip()
        tempfile = copy.copy(swefile)
        l = getFurthest(word,tempfile)

我想在这里发生的事情是,我想将 swefile 中尚未读取(即由 for 循环迭代)的部分发送到 getFurthest()!而且我无法发送 swefile 因为这会使整个内容被读取,因此 for 循环中的迭代将停止,对吗?那么我怎样才能只发送文本文件中已经读取到 getFurthest() 的部分,同时仍然能够在之后迭代它的其余部分?

如果您想避免重新打开文件,但又想读取它两次,您可以使用 seek():

import copy
def printtext(swefile):
    for row in swefile:
        print(row)
text = open("wordsv.txt","r",encoding='utf-8')
printtext(text)
text.seek(0)
printtext(text)

如果你只关心文字,你可以这样做:

import copy
def printtext(swefile):
    for row in swefile:
        print(row)
text = open("wordsv.txt","r",encoding='utf-8').readlines()
text2 = copy.copy(text)
printtext(text)
printtext(text2)

这里 textwordsv.txt 中行的列表,然后您将列表复制到 text2(即更改 text 不会更改 text2) .

您的行 text2 = copy.copy(text) 不起作用,因为文本只是一个文件对象。对"copy"文件中的文本进行如下操作:

text2 = text.read()

请注意,您不要复制实际的文本(内容),因为字符串是不可变的。

或者,如果您出于某种原因确实想要结束两个文件,最好使用 shutil.copy 来复制它:

import shutil

path = "wordsv.txt"
path2= "wordsv2.txt"
shutil.copy(path, path2)
with open(path, encoding='utf-8') as text, open(path2, encoding='utf=8') as text2:
    # Do something with text, text2 here