创建和重命名文件的问题

时间:2018-01-24 09:48:21

标签: python python-2.7 command-line

在Python中,我使用名为tempo2的天文命令行工具编写了一个小脚本,该工具创建了一个名为' polyco_new.dat'的文件。我想使用文件路径重命名新创建的文件。

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')

然而,我得到的错误是' polyco_new.dat'不存在(没有这样的文件或目录),即使我知道它是由tempo2工具创建的。

如何使此代码有效?

1 个答案:

答案 0 :(得分:1)

问题可能在于tempo2创建文件的默认目录与启动Python脚本的当前工作目录之间的区别。要修复它,请执行以下操作:

# 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))
相关问题