如何在python中复制文本文件

2024-10-01 15:37:42 发布

您现在位置: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())

但这是不可能的,TypeError:cannot serialize'_io.TextIOWrapper'对象。 所以我想知道是否有一个好的方法来“克隆”文本变量,这样我就可以再次打印所有的行了。但我不知道怎样才能解决这个问题。在


这里有一个更大的背景,因为我还没能用你的建议来解决我的问题:

^{pr2}$

我想在这里发生的事情是,我想把swefile中尚未被读取的部分发送到getFurthest()!我不能发送swefile,因为这会使整个内容都被读取,所以for循环中的迭代将停止,对吗?那么,如何才能只发送文本文件中已被读取到getFurthest()的部分,而之后仍然能够迭代其余部分呢?在


Tags: textinimporttxtfordefopenrow
3条回答

或者,如果由于某种原因您确实希望得到两个文件,最好使用^{}来复制它:

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

如果您试图避免重新打开文件,但又想读取两次,可以使用^{}

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)

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

^{pr2}$

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

您的行text2 = copy.copy(text)不起作用,因为文本只是一个文件对象。要“复制”文件中的文本,请执行以下操作:

text2 = text.read()

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

相关问题 更多 >

    热门问题