简体   繁体   English

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

[英]Python - Path/Folder/File creation

I am running the following block of code to create the path to a new file: 我正在运行以下代码块来创建新文件的路径:

# 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()

The code run as intended with the exception that it creates and saves the files on the directory: /home/user/test_scripts/ configs/ instead on the indented one that should be: /home/user/test_scripts/configs/ device_name[-1]/ . 该代码按预期运行,但会创建以下文件并将其保存在以下目录中:/ home / user / test_scripts / configs /,而不是缩进的文件应为:/ home / user / test_scripts / configs / device_name [-1 ] /

Please advise. 请指教。

Regards, 问候,

./daq ./daq

Try using os.path.join(base_path, new_path) [Reference] instead of string concatenation. 尝试使用os.path.join(base_path, new_path) [参考]代替字符串串联。 For example: 例如:

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")

Although I don't get why you're creating a directory with device_name[ -1 ] and as a file name using device_name[ 0 ]. 尽管我不明白为什么要使用device_name [ -1 ]和使用device_name [ 0 ]作为文件名创建目录。

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

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