我有一个 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/