[英]How do I modify a filepath using the os.path module?
我的密碼
import os.path #gets the module
beginning = input("Enter the file name/path you would like to upperify: ")
inFile = open(beginning, "r")
contents = inFile.read()
moddedContents = contents.upper() #makes the contents of the file all caps
head,tail = os.path.split(beginning) #supposed to split the path
new_new_name = "UPPER" + tail #adds UPPER to the file name
final_name = os.path.join(head + new_new_name) #rejoins the path and new file name
outFile = open(final_name, "w") #creates new file with new capitalized text
outFile.write(moddedContents)
outFile.close()
我只是想更改文件名,以通過os.path.split()將UPPER添加到文件名的開頭。 難道我做錯了什么?
更改
final_name = os.path.join(head + new_new_name)
至
final_name = head + os.sep + new_new_name
head
從os.path.split
沒有到底斜線。 當您通過連接head
和new_new_name
來連接它們時
head + new_new_name
您無需添加缺少的斜杠,因此整個路徑將無效:
>>> head, tail = os.path.split('/etc/shadow')
>>> head
'/etc'
>>> tail
'shadow'
>>> head + tail
'/etcshadow'
解決方案是正確使用os.path.join
:
final_name = os.path.join(head, new_new_name)
聲明:本站的技術帖子網頁,遵循CC BY-SA 4.0協議,如果您需要轉載,請注明本站網址或者原文地址。任何問題請咨詢:yoyou2525@163.com.