I am new to python.
I have a set of commands which I want to convert to a python script.

commands are

foreach f (`cat ../etc/l.list`)
echo $f
mkdir "$f"
cd "$f"
cp ../r/"$f".txt .
cd ..
end

I succeded in creating folders with respective names as listed in l.list,
but struggling to copy respective files "$f".txt to respective f folders

this is what i put down till now


import os, sys
import shutil

fil = open("../etc/l.list")
lines = fil.readlines()
fil.close()
for f in lines:
dirname = "f"
if not os.path.isdir("./" + f + "/"):
os.mkdir("./" + f + "/")

can sobody tell me how to copy. tried copytree, but failed.

Dani AI

Generated

A compact, robust pattern that picks up the idea from and the Python-3 approach from but avoids the common pitfalls (trailing newlines, missing sources, and misuse of shutil.copytree).

from pathlib import Path
import shutil
import sys

list_path = Path('..') / 'etc' / 'l.list'
r_dir = Path('..') / 'r'
cwd = Path.cwd()

if not list_path.exists():
    sys.exit('list file not found: {}'.format(list_path))

for raw in list_path.read_text(encoding='utf-8').splitlines():
    name = raw.strip()
    if not name:
        continue
    target = cwd / name
    target.mkdir(parents=True, exist_ok=True)
    src = r_dir / (name + '.txt')
    if not src.exists():
        print('warning: missing', src)
        continue
    try:
        shutil.copy2(src, target / src.name)
    except Exception as e:
        print('failed to copy {} -> {}: {}'.format(src, target, e))

Why this helps: pathlib makes joins and mkdirs portable and clear; reading with splitlines() + strip() avoids creating empty or misnamed folders; shutil.copy2 copies individual files (preserving timestamps) — shutil.copytree is for whole directory trees and will fail if the source is a file or the destination already exists. Use absolute paths (for example compute base = Path(file).resolve().parent) if the script might be run from another working directory.

Troubleshooting tips: run a dry run (print the planned copies) before executing, check for permission errors, verify that l.list has exactly the base names you expect (no extra extensions), and handle filenames with spaces by treating each line as a single name (strip only leading/trailing whitespace). This should resolve the copying issue reported by while keeping the solution simple and reliable.

Recommended Answers

All 2 Replies

I have a nice module for such tasks, which I call kernilis.path, which implements a useful 'path" class which methods access the functions of modules os, os.path and shutil. Just unzip the attached file and put the kernilis folder somewhere in your python path. Now the program looks like this

from kernilis.path import path, fullpath

wd = path.cwd()

with open(fullpath("..")/"etc"/"l.list") as inFile:
  for f in inFile:
    f = f.strip()
    dire = wd/f
    if not dire.isdir():
      dire.mkdir()
    name = f + ".txt"
    (wd/"r"/name).copy(dire)

In python 3:

import os
import shutil

with open('../l.list') as f:
  for line in f:
    line = line.strip()
    print(line)
    os.mkdir(line)
    shutil.copy('../' + line, line + '/' + line + '.txt')

It is pretty much the same as your shell script.

: Nice library.

Be a part of the DaniWeb community

We're a friendly, industry-focused community of developers, IT pros, digital marketers, and technology enthusiasts meeting, networking, learning, and sharing knowledge.