简体   繁体   中英

How to read files in other directory in python

I want to open and read some files from different folders in 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 "/". 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? 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? 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

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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