Sah*_*and 0 python text clone file
这就是我想要做的事情:
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())
Run Code Online (Sandbox Code Playgroud)
但这是不可能的,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)
Run Code Online (Sandbox Code Playgroud)
我想在这里发生的事情是,我想发送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)
Run Code Online (Sandbox Code Playgroud)
如果您只关心文本,可以这样做:
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)
Run Code Online (Sandbox Code Playgroud)
这text是一个列表中的行wordsv.txt,然后将列表复制到text2(即更改text不会更改text2).