如何修改使用os.path中模块文件路径?(How do I modify a filepath u

2019-10-20 04:21发布

我的代码

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这样的鞋面添加到开始到文件名()。 难道我做错了什么?

Answer 1:

heados.path.split没有到底斜线。 当你加入的headnew_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)


Answer 2:

更改

final_name = os.path.join(head + new_new_name)

final_name = head + os.sep + new_new_name


文章来源: How do I modify a filepath using the os.path module?