如何使用os.path模块修改文件路径? [英] How do I modify a filepath using the os.path module?

查看:90
本文介绍了如何使用os.path模块修改文件路径?的处理方法,对大家解决问题具有一定的参考价值,需要的朋友们下面随着小编来一起学习吧!

问题描述

我的代码

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添加到文件名的开头.我在做错什么吗?

I'm just trying to change the file name to add UPPER to the beginning to the file name via os.path.split(). Am I doing something wrong?

推荐答案

head末尾没有斜杠.通过连接headnew_new_name来加入

head from os.path.split doesn't have a trailing slash in the end. When you join the head and new_new_name by concatenating them

head + new_new_name 

您不会添加缺少的斜杠,因此整个路径将无效:

you don't add that missing slash, so the whole path becomes invalid:

>>> head, tail = os.path.split('/etc/shadow')
>>> head
'/etc'
>>> tail
'shadow'
>>> head + tail
'/etcshadow'

解决方案是使用 os.path.join 正确:

The solution is to use os.path.join properly:

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

这篇关于如何使用os.path模块修改文件路径?的文章就介绍到这了,希望我们推荐的答案对大家有所帮助,也希望大家多多支持IT屋!

查看全文
登录 关闭
扫码关注1秒登录
发送“验证码”获取 | 15天全站免登陆