【问题标题】:create file object in python 3.7在 python 3.7 中创建文件对象
【发布时间】:2019-07-04 08:54:47
【问题描述】:

我有 python 2.7 代码,它创建了一个内置文件对象,它返回一个文件对象<type 'file'>

 file(os.path.join('/tmp/test/', 'config.ini'))

我在 python 3.7 中更改的代码如下,它返回 <class '_io.TextIOWrapper'>

 open(os.path.join('/tmp/test/', 'config.ini'))

如何在 python 3 中获取文件对象类型

【问题讨论】:

标签: python-3.x file


【解决方案1】:

您可以以完全相同的方式使用它们。

file = open(os.path.join("/tmp/test/", "config.ini"))
print(file.read())  # Will print file contents

或者使用路径库:

from pathlib import Path
file = Path("/tmp/test") / "config.ini"
print(file.read_text())  # will do the same

您不是在寻找文件对象。您正在寻找一个可以让您读取和写入文件的对象。

【讨论】:

    猜你喜欢
    • 2016-03-19
    • 2017-04-16
    • 1970-01-01
    • 2022-08-18
    • 2018-08-08
    • 1970-01-01
    • 2020-03-09
    • 1970-01-01
    • 2016-10-19
    相关资源
    最近更新 更多