python - 如果要关闭文件,是否需要再次打开文件?
问题描述
在我的作业中,我应该在一个函数中阅读完一个文件后关闭它。但是,稍后我必须从另一个函数再次访问它。关闭文件是强制关闭文件的好习惯的要求,但我觉得没有必要,因为我需要稍后再次打开文件。有没有办法关闭文件并仍然从另一个功能访问它,或者我应该手动重新打开它。
示例代码:
def open(file):
filename = open(file, "r")
filename.read()
filename.close()
def access():
for line in filename:
print(line)
解决方案
没有什么说您必须在当前函数结束之前关闭文件,只是您必须确保文件已关闭。一种方法是将已经打开的文件access
作为参数传递给,并在access
返回后关闭它。例如,
def access1(fh):
for line in fh:
print(line)
def access2(fh):
# Do something else with the file
# This is the builtin open function, not the one in the question
with open(filename) as f:
access1(f)
f.seek(0) # Reset the file pointer for the next function
access2(f)
推荐阅读
- r - 如何有效地计算 data.table 的唯一(数字)列向量?
- reactjs - 在组件的本地状态下具有功能是不好的做法吗?
- redis - 在 Redis 中使用持久化时,密钥过期是否尊重原始时间?
- java - 使用 WebSocket 和 Spring 从 ActiveMQ 主题中删除旧消息
- java - JAVA Mail 和 Office 365 在连接时挂起
- python - 在 html 选择菜单中选择一个项目
- search - 通配符搜索会减慢 Splunk 结果搜索速度吗?
- c# - 如何检查组合框文本是否在下拉列表中?[视觉工作室]
- xaml - UWP ScrollBar 在我的用户控件中不可见
- c - 我可以在没有 posix_memalign 的情况下执行此代码吗?