为什么变量“x”没有正确定义路径

2024-06-01 09:50:52 发布

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

变量“x”未正确定义路径

我得到这个错误:

    with open(filename) as json_file:
FileNotFoundError: [Errno 2] No such file or directory: 'C:\\Users\\Sajid\\Desktop\\cuckoo (1)\\cuckoo\\storage\\analyses\\x\\reports\\report.json'
import os
from pathlib import Path
import json
import shutil    

for x in range(3,5):
    path = Path( r'C:\Users\Sajid\Desktop\cuckoo (1)\cuckoo\storage\analyses\x\reports')
    filename = os.path.join(path,"report.json")
    with open(filename) as json_file:
        data=json.load(json_file)
        var = os.path.join(str(path), os.path.basename(data['target']['file']['md5']))
        json_file.close()
        print(var)
        os.rename(filename,var)

我希望这段代码给出正确的路径


Tags: pathimport路径jsonosvaraswith
1条回答
网友
1楼 · 发布于 2024-06-01 09:50:52

看起来您希望x作为字符串中的变量进行计算。Python不会将字符串中的字符作为变量进行求值,除非您告诉它使用string^{}方法或format strings

在Python2.7+和Python3中+

path = Path( r'C:\Users\Sajid\Desktop\cuckoo (1)\cuckoo\storage\analyses\x\reports')

应该是

path = Path( r'C:\Users\Sajid\Desktop\cuckoo (1)\cuckoo\storage\analyses\{}\reports'.format(x))

在Python3.6+中(除了以前的版本)

path = Path(r'C:\Users\Sajid\Desktop\cuckoo (1)\cuckoo\storage\analyses\x\reports')

应该是

path = Path(f'C:\Users\Sajid\Desktop\cuckoo (1)\cuckoo\storage\analyses\{x}\reports')

相关问题 更多 >