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

时间:2019-06-20 20:38: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)

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

1 个答案:

答案 0 :(得分:2)

您似乎希望x被视为字符串中的变量。除非您使用字符串format方法或format strings告诉Python,否则Python不会将字符串中的字符作为变量进行评估。

在Python 2.7+和Python 3+中

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

在Python 3.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')