如何根据扩展名打开文件?

yip*_*iez 0 python file

我想在同一目录中打开任何 .txt文件.

在红宝石中我能做到

File.open("*.txt").each do |line|
       puts line
end
Run Code Online (Sandbox Code Playgroud)

在python我不能这样做它会给出一个错误

file = open("*.txt","r")
print(file.read())
file.close()
Run Code Online (Sandbox Code Playgroud)

它给出了一个错误无效的参数.

那有什么办法吗?

pul*_*hal 5

您可以直接使用该glob模块

import glob
for file in glob.glob('*.txt'):
    with open(file, 'r') as f:
        print(f.read())
Run Code Online (Sandbox Code Playgroud)