创建和重命名文件的问题

2024-09-28 01:24:49 发布

您现在位置:Python中文网/ 问答频道 /正文

我用Python编写了一个小脚本,使用一个名为tempo2的天文学命令行工具,它创建了一个名为“polyco_new.dat”的文件。我想使用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')

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

我怎样才能使这个代码工作


Tags: 文件工具pathimportnewosasnp
1条回答
网友
1楼 · 发布于 2024-09-28 01:24:49

问题可能在于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))

相关问题 更多 >

    热门问题