Python文本文件处理

问题描述 投票:2回答:5

请告知为什么这是行不通的,并且不显示错误:

def main(x, y):
    x=open('DCR.txt')
    x.read()
    print(x)
    y=open("111.txt", "a+")
    y=x
    y.close()

我正在尝试打开一个文件并将其内容移动到另一个文件。运行脚本时未创建111.txt

python text-files
5个回答
4
投票

y=x不会将内容从一个文件“移动”到另一个文件。它只是重新绑定名称(变量)y,以便之后,它引用与x相同的对象。

要将内容从一个类似文件的对象复制到另一个,请使用shutil.copyfileobj

shutil.copyfileobj

1
投票

您不能只是将新值分配给对象,并认为它将被写入文件。对于其他情况也是如此。您必须调用正确的方法。

这应该起作用:

from shutil import copyfileobj

with open('DCR.txt') as input:
    with open("111.txt", "a+") as output:
        copyfileobj(input, output)

0
投票

如果我没记错的话,赋值def main(x, y): x=open('DCR.txt') content_x = x.read() x.close() print(content_x) y=open("111.txt", "a+") y.write(content_x) y.close() 只是使变量y=x指向与y相同的文件描述符。实际上并没有移动任何数据。您应该改为调用x,其中y.write( x.read() )返回x.read()的内容。


0
投票

您的代码没有任何意义。您将x和y参数传递给函数,但同时覆盖两者(那么为什么要首先传递它们?):

DCR.txt

您没有使用从文件中读取的内容,您可能已经看到print(x)不会打印文件的内容,而是会打印文件句柄。

def main():
    x = open('DCR.txt')

您要用第一个替换第二个文件句柄,这实际上不做任何事情,因为您没有使用超过该点的文件句柄(除了关闭其中一个之外)。您可能想要做的是将第一个文件的内容写入第二个文件:

    content = x.read()

简化功能看起来像这样:

    y.write(content)

您在运行时遇到任何错误吗?


0
投票

您的版本

def main():
    x = open('DCR.txt')
    content = x.read()
    y = open("111.txt", "a+")
    y.write(content)

您可以这样做:

def main(x, y):
    x=open('DCR.txt')
    x.read() #you should assign it to a variable
    print(x)
    y=open("111.txt", "a+") 
    y=x #this line just assign the file object to y, not content
    y.close()
© www.soinside.com 2019 - 2024. All rights reserved.