Python-'str'对象没有属性'close' [英] Python - 'str' object has no attribute 'close'

查看:150
本文介绍了Python-'str'对象没有属性'close'的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我花了很多时间试图弄清楚为什么我编写的这几行代码不需要关闭属性:

I am having a great time trying to figure out why there doesn't need to be a closing attribute for this few lines of code I wrote:

from sys import argv
from os.path import exists

script, from_file, to_file = argv

file_content = open(from_file).read()
new_file = open(to_file, 'w').write(file_content)

new_file.close()

file_content.close()

我阅读了一些相关的文章和其他人的帖子,但是他们的脚本比我目前正在学习的脚本要复杂得多,所以我不知道为什么.

I read some things and other people's posts about this, but their scripts were a lot more complicated than what I'm currently learning, so I couldn't figure out why.

我正在努力学习Python,非常感谢您的帮助.

I am doing Learning Python the Hard Way and would appreciate any help.

推荐答案

file_content是一个字符串变量,它包含文件的内容-与文件没有关系.用open(from_file)打开的文件描述符将自动关闭:文件对象退出作用域后(在这种情况下,紧随.read()之后),文件会话将关闭.

file_content is a string variable, which contains contents of the file -- it has no relation to the file. The file descriptor you open with open(from_file) will be closed automatically: file sessions are closed after the file-objects exit the scope (in this case, immediately after .read()).

这篇关于Python-'str'对象没有属性'close'的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆