Warning: file_get_contents(/data/phpspider/zhask/data//catemap/2/python/304.json): failed to open stream: No such file or directory in /data/phpspider/zhask/libs/function.php on line 167

Warning: Invalid argument supplied for foreach() in /data/phpspider/zhask/libs/tag.function.php on line 1116

Notice: Undefined index: in /data/phpspider/zhask/libs/function.php on line 180

Warning: array_chunk() expects parameter 1 to be array, null given in /data/phpspider/zhask/libs/function.php on line 181
Python 将字符串从文件复制到新文件时获取AttributeError_Python_File_Copy - Fatal编程技术网

Python 将字符串从文件复制到新文件时获取AttributeError

Python 将字符串从文件复制到新文件时获取AttributeError,python,file,copy,Python,File,Copy,我正在编写一个简单的程序,它读取一个文件,复制其内容,并将复制的内容写入一个新文件。我认为我做的是正确的,因为当我打开“copyFile”时,原始文件的复制内容会作为字符串写入其中。我写过: copy = open('TestFile').read() #Open 'TestFile', read it into variable print("Copy of textfile:\t", copy) copyFile = open('copyText.txt

我正在编写一个简单的程序,它读取一个文件,复制其内容,并将复制的内容写入一个新文件。我认为我做的是正确的,因为当我打开
“copyFile”
时,原始文件的复制内容会作为字符串写入其中。我写过:

copy = open('TestFile').read()                   #Open 'TestFile', read it into variable
print("Copy of textfile:\t", copy)

copyFile = open('copyText.txt', 'w').write(copy) #Create new file, write in the copied text
copyText = copyFile.read()
print("New file :\t", copyText)
我可以打印文件的内容,但当我尝试打印副本时,我会出现以下错误:

Traceback (most recent call last):
    File "PATH/TO/THE/FILE/CALLED/copyText.py", line 14, in <module>
        copyText = copyFile.read()
AttributeError: 'int' object has no attribute 'read'
回溯(最近一次呼叫最后一次):
文件“PATH/TO/THE/File/CALLED/copyText.py”,第14行,在
copyText=copyFile.read()
AttributeError:“int”对象没有属性“read”
文件中只有一句话,所以我不明白我得到的错误

  • 文件
    write
    不返回
    io
    对象。它返回所写文本的长度
  • 我还建议您应该使用with语句从文件中写入和读取
  • 以下代码是为您的案例执行此操作的正确方法
copy=open('TestFile').read()#打开'TestFile',将其读入变量
打印(“文本文件的副本:\t”,副本)
长度=打开('copyText.txt','w')。写入(复制)#创建新文件,写入复制的文本
copyText=open('copyText.txt','r')。read()
打印(“新文件:\t”,copyText)
  • 这是您应该用于读写的解决方案
以open('TestFile','r')作为readfile的
:
copy=readfile.read()
打印(“文本文件的副本:\t”,副本)
将open(“copyTest.txt”,“w”)作为writefile:
长度=writefile.write(复制)
打印(“写入文件的长度”,长度)
打开(“copyTest.txt”,“r”)作为读取文件:
copyText=readfile.read()
打印(“新文件:\t”,copyText)
输出

Copy of textfile:    this is a sentence

Length written to file 19
New file:    this is a sentence
测试文件:

这是一个句子


看起来
write
函数正在输出写入文件的字符数,这意味着您正试图在
int
上调用
read

如果要在以后读取文件文本,则在尝试写入文件之前,需要将文件存储在变量中。这可以通过如下方式实现

copy = open('TestFile').read()                   #Open 'TestFile', read it into variable
print("Copy of textfile:\t", copy)

copyFile = open('copyText.txt', 'w') #Create new file
copyFile.write(copy) # write in the copied text
copyText = copyFile.read()
print("New file :\t", copyText)