未能在open()中写入具有目录/文件名形式的文件

2024-04-19 12:41:15 发布

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

我在开发一个复杂的脚本时遇到了一个问题,并用几行代码复制了它:

import os

i=2
content_pbs = "test"
os.popen('if [ -d f_bf_'+str(i)+' ]; then rm -rf f_bf_'+str(i)+\
         '; fi; mkdir f_bf_'+str(i)+';')
#Write to a file
f = open('f_bf_'+str(i)+'/my_pbs', 'w')
f.write(content_pbs)
f.close()

错误是:

Traceback (most recent call last):
File "test.py", line 7, in <module>
f = open('f_bf_'+str(i)+'/my_pbs', 'w')
FileNotFoundError: [Errno 2] No such file or directory: 'f_bf_2/my_pbs'

如果popen替换为system,则不会显示任何错误,并且文件已正确写入。或者只修改f = open('my_pbs', 'w'),同时保持popen,没有错误,文件看起来很好。如果我用2.7.10运行原始代码,一切正常。我的问题是,我原来的剧本怎么了?仅供参考,我使用python3.6.4。可能是3.6.4版的错误。你知道吗


Tags: 文件代码testimport脚本osmy错误
1条回答
网友
1楼 · 发布于 2024-04-19 12:41:15

最好使用当前推荐的子流程.Popen(https://docs.python.org/3.6/library/subprocess.html),例如:

def rnsystem (cmd, showoutput=True):
    p = subprocess.Popen(cmd, stdout=subprocess.PIPE, 
                              stderr=subprocess.PIPE, 
                              universal_newlines=True, 
                              shell=True)
    (out, err) = p.communicate()
    ret      = p.wait()
    out      = out.split('\n')
    err      = err.split('\n')
    ret_tf   = True if ret == 0 else False
    if showoutput: 
        if ret_tf:
            for o in out: 
                print(o)
        else: 
            for e in err: 
                print(e)
    return {'output': out, 'error': err, 'status': ret, 'status_tf': ret_tf}

相关问题 更多 >