简体   繁体   中英

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

Please advise.

Regards,

./daq

Try using os.path.join(base_path, new_path) [Reference] instead of string concatenation. 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 ].

The technical post webpages of this site follow the CC BY-SA 4.0 protocol. If you need to reprint, please indicate the site URL or the original address.Any question please contact:yoyou2525@163.com.

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