繁体   English   中英

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

[英]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

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)

暂无
暂无

声明:本站的技术帖子网页,遵循CC BY-SA 4.0协议,如果您需要转载,请注明本站网址或者原文地址。任何问题请咨询:yoyou2525@163.com.

 
粤ICP备18138465号  © 2020-2024 STACKOOM.COM