繁体   English   中英

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

[英]Python - Path/Folder/File creation

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

# 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 / device_name [-1 ] /

请指教。

问候,

./daq

尝试使用os.path.join(base_path, new_path) [参考]代替字符串串联。 例如:

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 ]作为文件名创建目录。

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM