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.

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.

@Gribouillis: 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.