Isma Rekathakusuma
Isma Rekathakusuma

Reputation: 1152

Python os.walk doesn't copy files from upper directory

I have some files which are generated in 2 different directory

D:\project\external\gerenateExternal
consist of : 1.txt, 2.txt, 3.txt

D:\project\main\generateMain
consisst of : a.txt, b.txt, 3.txt

I want to copy all files from that different directory to D:\project\main\targetDir

My python is in D:\project\main\copy.py

import os
import shutil
import os.path as path

pyfile = os.path.dirname(os.path.abspath(__file__))

pathExternal = os.path.abspath(pyfile + '\..\external\gerenateExternal')
pathMain = os.path.abspath(pyfile + '\generateMain')

targetdir = os.path.abspath(pyfile + '\targetDir')

for p in [ pathMain , pathExternal ]:
    print(p)
    for path, dirs, files in os.walk(p):
        print(files)
        for file in files:
            if file.endswith(".txt"):
                shutil.copy(os.path.join(path, file), targetdir)

The only files that can be copy is from pathMain I found that any files in folder same level or below current python file (copy.py) can be copied But if I have files from upper directory from current python file (copy.py) can't be copied.

How to copy files from upper directory from current python file ?

Upvotes: 0

Views: 124

Answers (2)

Timus
Timus

Reputation: 11321

I don't quite understand why you are using os.walk: You know the 2 folders with the files, you could use them directly?

You could try the following:

from pathlib import Path
from shutil import copy
from itertools import chain

pyfile = Path(__file__).resolve().parent  # Should be: D:\project\main
pathExternal = pyfile.parent / Path(r'external\generateExternal')  # Should be: D:\project\external\gerenateExternal
pathMain = pyfile / Path('generateMain')  # Should be: D:\project\main\generateMain
targetdir = pyfile / Path('targetDir')  # Should be: D:\project\main\targetDir
targetdir.mkdir(exist_ok=True)  # In case targetdir doesn't exist

for file in chain(pathExternal.glob('*.txt'), pathMain.glob('*.txt')):
    copy(file, targetdir)

If you want something more os.walk-like you could replace the loop with

...
for file in pyfile.parent.rglob('*.txt'):
    copy(file, targetdir)

Upvotes: 1

flyakite
flyakite

Reputation: 799

The code should work just fine. You have a minor TypO in "gerenateExternal". Please check, if the actual directory has the same name.

In addition, for avoiding "\t" in '\targetDir' is interpreted as tab, I would suggest to escape the character, use a forward slash or join the directory, e.g.

targetdir = os.path.abspath(pyfile + '\\targetDir')

Upvotes: 0

Related Questions