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

标签 python python-3.x file input io

我有一个 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 中实现这一点?

最佳答案

您可以使用 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]

关于python - 如何仅使用其扩展名打开文件?,我们在Stack Overflow上找到一个类似的问题: https://stackoverflow.com/questions/40452536/

相关文章:

python - Python 中 os.scandir() 目录树中的条目(文件和文件夹)列表

python - 为什么 Python 2.7 对 x64 上的 GetDC() 返回的 HDC 进行签名扩展?

python - PIL Image.open 创建损坏的图像

python-3.x - 如何使用python将文件夹从本地上传到GCP存储桶

Java:从utf-8文件中读取字节

c - 使用程序的输出作为同一程序的输入

python - 简单的 Python UDP 服务器 : trouble receiving packets from clients other than localhost

python - 抓取列表的特定索引

Python3 : Resize rectangular image to a different kind of rectangle, 保持比例并用黑色填充背景

java - 如何将文件从一个文件夹移动到另一个文件夹