python更改文件路径_如何在Python中正确更改文件路径的名称?

1586010002-jmsa.png

My code

specFileName = input("Enter the file path of the program you would like to capslock: ")

inFile = open(specFileName, 'r')

ified = inFile.read().upper()

outFile = open(specFileName + "UPPER", 'w')

outFile.write(ified)

outFile.close()

print(inFile.read())

This is basically make to take in any file, capitalize everything, and put it into a new file called UPPER"filename". How do I add the "UPPER" bit into the variable without it being at the very end or very beginning? As it won't work like that due to the rest of the file path in the beginning and the file extension at the end. For example, C:/users/me/directory/file.txt would become C:/users/me/directory/UPPERfile.txt

解决方案

Depending on exactly how you're trying to do this, there's several approaches.

First of all you probably want to grab just the filename, not the whole path. Do this with os.path.split.

>>> pathname = r"C:\windows\system32\test.txt"

>>> os.path.split(pathname)

('C:\\windows\\system32', 'test.txt')

Then you can also look at os.path.splitext

>>> filename = "test.old.txt"

>>> os.path.splitext(filename)

('test.old', '.txt')

And finally string formatting would be good

>>> test_string = "Hello, {}"

>>> test_string.format("world") + ".txt"

"Hello, world.txt"

Put 'em together and you've probably got something like:

def make_upper(filename, new_filename):

with open(filename) as infile:

data = infile.read()

with open(new_filename) as outfile:

outfile.write(data.upper())

def main():

user_in = input("What's the path to your file? ")

path = user_in # just for clarity

root, filename = os.path.split(user_in)

head,tail = os.path.splitext(filename)

new_filename = "UPPER{}{}".format(head,tail)

new_path = os.path.join(root, new_filename)

make_upper(path, new_path)

  • 1
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值