如何仅通过文件扩展名打开文件?

10

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

可能是重复的问题:Python: script's directory - Jean-François Fabre
@Jean-FrancoisFabre,那个问题是关于Python的realpath目录的。在我的情况下,我想打开一个文件,而不需要明确提供它的名称(即仅基于其文件扩展名),该文件恰好位于脚本的realpath目录中。对问题进行了一些小修改,以使区别更清晰。 - Yannis
3个回答

9

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

这会搜索工作目录,而不是脚本目录。 - ShadowRanger
@ShadowRanger,我更新了我的问题,因为对我来说,工作目录和脚本目录没有区别。感谢您指出这一点。 - Yannis
1
@ShadowRanger使用相对路径打开文件,正如OP所做的那样,也会在工作目录中打开。我猜这就是OP的意思。 - Mureinik
@Mureinik,您的猜测是正确的,尽管我在最初的帖子中应该更清楚地表述。已编辑问题,现在应该是清楚的了。 - Yannis

7
您也可以使用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')

来更改工作目录。


1
自从Python 3.4版本以后,可以使用优秀的pathlib库。它提供了一个glob方法,使得按照扩展名筛选变得容易:
from pathlib import Path

path = Path(".")  # current directory
extension = ".txt"

file_with_extension = next(path.glob(f"*{extension}"))  # returns the file with extension or None
if file_with_extension:
    with open(file_with_extension):
        ...

网页内容由stack overflow 提供, 点击上面的
可以查看英文原文,
原文链接