user90465
user90465

Reputation: 187

Issue with creating and renaming a file

In Python I wrote a little script, using an astronomy command line tool, called tempo2, which creates a file called 'polyco_new.dat'. I want to rename the newly created file, by using the filepath.

import os, sys
import numpy as np

with open('paths.txt', 'r') as paths_list:
    for file_path in paths_list:
        data = np.loadtxt(file_path.strip())
        filename = file_path[-26:-5]

        # creates the 'polyco_new.dat'-file
        os.system("tempo2 -tempo1 -polyco  \"%f %f 120 15 12 @ 0\" -f  ephemerides.par" %(t0, te))  

        # renames the file
        os.rename('polyco_new.dat', 'polycox_'+filename+'.dat')

However, I get the error that the 'polyco_new.dat' does not exist (no such file or directory), even though I know it is created by the tempo2 tool.

How can I make this code work?

Upvotes: 0

Views: 30

Answers (1)

Ma0
Ma0

Reputation: 15204

The problem probably lies to the difference between the directory used by default by tempo2 to create files and the current working directory from where your Python script is launched. To fix it, do:

# creates the 'polyco_new.dat'-file
os.system("tempo2 -tempo1 -polyco  \"%f %f 120 15 12 @ 0\" -f  ephemerides.par" %(t0, te))  

# assuming the file was created in C:\some\directory
os.chdir(r'C:\some\directory')
os.rename('polyco_new.dat', 'polycox_{}.dat'.format(filename))

Upvotes: 1

Related Questions