变量“ 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)
我希望这段代码给出正确的路径
答案 0 :(得分:2)
您似乎希望x
被视为字符串中的变量。除非您使用字符串format
方法或format strings告诉Python,否则Python不会将字符串中的字符作为变量进行评估。
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))
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')