我正在运行以下代码块来创建新文件的路径:
# Opens/create the file that will be created
device_name = target_device["host"].split('.')
path = "/home/user/test_scripts/configs/" + device_name[-1] + "/"
print(path)
# Check if path exists
if not os.path.exists(path):
os.makedirs(path)
# file = open(time_now + "_" + target_device["host"] + "_config.txt", "w")
file = open(path + time_now + "_" + device_name[0] + "_config.txt", "w")
# Time Stamp File
file.write('\n Create on ' + now.strftime("%Y-%m-%d") +
' at ' + now.strftime("%H:%M:%S") + ' GMT\n')
# Writes output to file
file.write(output)
# Close file
file.close()
代码按预期运行,但它会在目录:/home/user/test\u scripts/configs/上创建和保存文件,而不是在缩进的目录:/home/user/test\u scripts/configs/device\u name[-1]/上
请告知
谨致问候
/数据采集
尝试使用
os.path.join(base_path, new_path)
[Reference]而不是字符串连接。例如:虽然我不明白你为什么要用设备名[-1]创建一个目录,并用设备名[0]创建一个文件名
相关问题 更多 >
编程相关推荐