Python路径/文件夹/文件创建

2024-04-19 04:25:38 发布

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

我正在运行以下代码块来创建新文件的路径:

# 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]/

请告知

谨致问候

/数据采集


Tags: 文件path代码nametesthosttargethome
1条回答
网友
1楼 · 发布于 2024-04-19 04:25:38

尝试使用os.path.join(base_path, new_path)[Reference]而不是字符串连接。例如:

path = os.path.join("/home/user/test_scripts/configs/", device_name[-1])
os.makedirs(path, exist_ok=True)

new_name = time_now + "_" + device_name[0] + "_config.txt"
with open(os.path.join(path, new_name), "w+") as file:
    file.write("something")

虽然我不明白你为什么要用设备名[-1]创建一个目录,并用设备名[0]创建一个文件名

相关问题 更多 >