Copy file with os.system

4.5k Views Asked by At

I have several files named as follow a_b.nc a_c.nc a_d.nc. I would like to copy/rename those files using a loop.

I tried using the following code:

import os
stations = ["b" , "c" , "d"]
inbasedir = "/home/david/test_pals/PALS/sites_lai/"
varname = "a_"
for station in stations:
    os.chdir(inbasedir)
    os.system("cp ${varname}${station}.nc ${varname}${station}_lai.nc")

The code produces no error, but at the same time it produces no output at all :)

Does anyone has an idea about how to produce the desired output?

1

There are 1 best solutions below

0
Anthony On BEST ANSWER

Does anyone has an idea about how to produce the desired output?

You have to modify your string's syntax from${varname}${station} to something like this: os.system("cp {0}{1}.nc ${0}${1}_lai.nc".format(varname, station)) and that would work. I would have done it this way:

import os
rename = ['f1.txt', 'f2.txt'] # list of files to rename
cur_dir = os.path.dirname(os.path.abspath(__file__)) # the dir with files
files = os.listdir() # list of all files in directory 

for f in files:
    if f in rename:
        os.popen("cp {0} {1}".format(f, f + "_renamed"))

In my present directory I have created these files f1.txt and f2.txt. After your run os.popen("cp {0} {1}".format(f, f + "_renamed")) I've got all files from the rename list changed.

Remark: Here is a description of popen and what is does.