簡體   English   中英

如何在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())

但是不可能,TypeError:無法序列化“ _io.TextIOWrapper”對象。 因此,我想知道是否存在一種“克隆”文本變量的好方法,以便可以再次打印所有行。 我知道我可以再次讀取文件,但是該答案不能解決我遇到的更大問題,因此,有關如何完成此操作的任何建議都是有幫助的。


這是一個較大的背景,因為我無法通過您的建議解決問題:

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 )。

另外,如果您確實出於某種原因想要結束兩個文件,最好使用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

您的一行text2 = copy.copy(text)不起作用,因為text僅是文件對象。 要“復制”文件中的文本,請執行以下操作:

text2 = text.read()

請注意,由於字符串是不可變的,因此您不會復制實際的文本(內容)。

暫無
暫無

聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.

 
粵ICP備18138465號  © 2020-2024 STACKOOM.COM