如何仅使用其扩展名打开文件?

新手上路,请多包涵

我有一个 Python 脚本,它打开位于 特定目录( _工作目录_)中的特定文本文件并执行一些操作。

(假设如果目录中有一个文本文件,那么它永远不会超过一个这样 .txt 文件)

 with open('TextFileName.txt', 'r') as f:
    for line in f:
        # perform some string manipulation and calculations

    # write some results to a different text file
    with open('results.txt', 'a') as r:
        r.write(someResults)

我的问题是如何让脚本 在目录中找到文本 (.txt) 文件并在不显式提供其名称(即不提供“TextFileName.txt”)的情况下打开它。因此,运行此脚本不需要打开哪个文本文件的 _参数_。

有没有办法在 Python 中实现这一点?

原文由 Yannis 发布,翻译遵循 CC BY-SA 4.0 许可协议

阅读 543
2 个回答

您可以使用 os.listdir 获取当前目录中的文件,并按扩展名过滤它们:

 import os

txt_files = [f for f in os.listdir('.') if f.endswith('.txt')]
if len(txt_files) != 1:
    raise ValueError('should be only one txt file in the current directory')

filename = txt_files[0]

原文由 Mureinik 发布,翻译遵循 CC BY-SA 3.0 许可协议

您还可以使用 glob 这比 os 更容易

import glob

text_file = glob.glob('*.txt')
# wild card to catch all the files ending with txt and return as list of files

if len(text_file) != 1:
    raise ValueError('should be only one txt file in the current directory')

filename = text_file[0]

glob 搜索由 os.curdir

您可以通过设置更改到工作目录

os.chdir(r'cur_working_directory')

原文由 Rraki 发布,翻译遵循 CC BY-SA 4.0 许可协议

撰写回答
你尚未登录,登录后可以
  • 和开发者交流问题的细节
  • 关注并接收问题和回答的更新提醒
  • 参与内容的编辑和改进,让解决方法与时俱进
推荐问题