0

我的代码

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

4

2 回答 2

2

改变

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

final_name = head + os.sep + new_new_name
于 2014-05-20T17:09:13.407 回答
1

headfromos.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)
于 2014-05-20T17:07:30.490 回答