简体   繁体   English

如何读取 python 中其他目录中的文件

[英]How to read files in other directory in python

I want to open and read some files from different folders in Python3.我想从 Python3 的不同文件夹中打开和读取一些文件。 The structure is like:结构如下:

snapshot
  - folder1
      - file 1
      - file 2
  - folder2
      - file 3
      - file 4

I tried using pathlib , but it is showed "\" instead "/".我尝试使用pathlib ,但显示的是“\”而不是“/”。 Is there other way to do it?还有其他方法吗? The ideal result I want is this:我想要的理想结果是这样的:

"./snapshot/folder1/file 1"
"./snapshot/folder1/file 2"
"./snapshot/folder1/file 3"
"./snapshot/folder1/file 4"

This is my code:这是我的代码:

folders = Path('Snapshot/')**strong text**
for folder in folders.iterdir():
    files = Path(f'./{folder}/')
    for file in files.iterdir():      

Why don't you just:你为什么不只是:

from pathlib import Path
folders = Path('Snapshot/')
for folder in folders.iterdir():
    files = Path(folder)
    for file in files.iterdir():  

The string expansion is not needed.不需要字符串扩展。

I also don't know what you mean with '\'.我也不知道'\'是什么意思。 Why do you care at all?你为什么在乎呢? I thought you want to read the contents of a file?我以为你想读取文件的内容?

perhaps you show the lines after the last for loop?也许您在最后一个 for 循环之后显示行? Example:例子:

from pathlib import Path

folders = Path('Snapshot/')
for folder in folders.iterdir():
    if not folder.is_dir():
        continue
    entries = Path(folder)
    for entry in entries.iterdir():
        if not entry.is_file():
            continue
        print("fname", str(entry))
        with open(entry, "rb") as fin:
            data = fin.read()
        print(len(data), "bytes")

Are you running on windows?你在 windows 上运行吗? Then it would be possible, that your path name is 'normalized' (using the default directory separator '\')那么有可能,您的路径名是“规范化的”(使用默认目录分隔符“\”)

import os

dirpath = 'snapshot'
for root, dirnames, fnames in os.walk(dirpath):
    for fname in fnames:
        print(os.path.join('.', root, fname))
import os

for folder in os.listdir('snapshot'):

    folder_path = os.path.join('snapshot', folder)

    for file in os.listdir(folder_path):

        # do stuff

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM