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

2024-06-11 21:10:35 发布

您现在位置:Python中文网/ 问答频道 /正文

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


Tags: 文件in目录txt脚本foraswith
3条回答

从Python版本3.4开始,就可以使用伟大的^{}库。它提供了一种^{}方法,可以方便地根据扩展进行筛选:

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):
        ...

您还可以使用比os更简单的glob

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')

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

相关问题 更多 >