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

这个问题在这里已经有了答案:

  • 如何列出目录的所有文件? 31个答案

  • 使用os.listdir

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

    而是使用glob.glob来选择仅匹配给定模式的文件:

    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/20053.html

    上一篇: How can I automatically open all text files in a given folder?

    下一篇: Automatically creating a list in Python