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

时间:2018-12-16 16:15:15

标签: python python-3.x operating-system

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

# 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_scripts / configs / ,而不是缩进的文件应位于:/ home / user / test_scripts / configs / 设备名称[-1] /

请告知。

此致

./ daq

1 个答案:

答案 0 :(得分:0)

尝试使用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")

尽管我不明白为什么要使用device_name [ -1 ]创建目录,并使用device_name [ 0 ]作为文件名。