How can I automatically open all text files in a given folder?

This question already has an answer here:

  • How do I list all files of a directory? 31 answers

  • Use os.listdir :

    for f in os.listdir("/Users/Desktop/File/"):
        with open(f, "r", encoding="UTF-16") as read_file:
    

    Use glob.glob instead to select only files matching a given pattern:

    for f in glob.glob("/Users/Desktop/File/*.txt"):
        with open(f, "r", encoding="UTF-16") as read_file:
    

    您可以改为使用新的Python库pathlib

    from pathlib import Path
    
    p = Path.cwd() 
    files = [x for x in p.iterdir()]
    for file in files:
        with open(str(file), 'r', encoding="UTF-16") as f:
            # ....
    
    链接地址: http://www.djcxy.com/p/20054.html

    上一篇: 如何获取文件路径+文件名到列表中?

    下一篇: 我如何自动打开给定文件夹中的所有文本文件?