簡體   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