python - 根据文件扩展名打开语句

标签 python python-3.x

我需要处理目录中的两种类型的文件 - .txt.gz。 为此,有两种类型的打开语句:

.gz 文件:

with gzip.open(file_name, 'rt', encoding='utf-8') as f:
    line = next(f)
    while line:
        some code

.txt 文件:

with open(file_name, 'r', encoding='utf-8') as f:
    line = next(f)
    while line:
        some code

任何进一步的处理命令都是完全相同的。现在我看到了两个选项来处理这两种文件类型:

选项 1 - 使用仅 open 语句不同的两个相同函数。听起来很丑……

选项 2 - 使用 if 构造如下:

if ext == '.gz':
    f = gzip.open(file_name, 'rt', encoding='utf-8')
elif ext == '.txt':
    f = open(file_name, 'r', encoding='utf-8')

    line = next(f)
    while line:
        some code

但对我来说它仍然看起来很尴尬:/

问题:Python 3.x 中根据文件扩展名使用 open 语句的 pythonic 方式是什么?

最佳答案

为什么不呢:

with (gzip.open if ext==".gz" else open)(file_name, 'rt', encoding='utf-8') as f:

with 的第一个参数是一个三元表达式,您可以根据扩展决定使用哪个函数。我在这两种情况下都使用了 'rt',这是标准 open 的默认设置。该方法的优点是可以避免复制/粘贴并能够使用上下文管理器。

也许可以使用辅助函数创建一些通用函数:

def myopen(file_name)
  return (gzip.open if os.path.splitext(file_name)[1]==".gz" else open)(file_name, 'rt', encoding='utf-8')

像这样使用:

with myopen(file_name):

关于python - 根据文件扩展名打开语句,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/49224375/

相关文章:

python - 使用适用于 Python 的 Google API - 我从哪里获取 client_secrets.json 文件?

python - 如果 python 赋值不返回值我们怎么能做 a = b = c = 42

python - 从字典中保存关系 sqlalchemy 对象

python-3.x - python选择子集,其中df列值包含数组中的值之一

python 3 : doctest helper/internal functions?

python - Django 1.8 : Join latest entry to foreign key

python - 如何在 dask 中执行分组聚合后保留分区

python - 在 Python 中从(字符串)元组写入 csv

Python 2 与 3 原始字节输出

python - 标签上的 Tkinter 标签