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)
- 这是您应该用于读写的解决方案
:
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)