如何使用os.path模块修改文件路径?

时间:2014-05-20 17:00:24

标签: python filepath self-modifying

我的代码

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添加到文件名的开头。我做错了吗?

2 个答案:

答案 0 :(得分:2)

更改

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

final_name = head + os.sep + new_new_name

答案 1 :(得分:1)

来自head

os.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)