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

0 投票
2 回答
626 浏览
提问于 2025-04-18 07:02

我的代码

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())

这个代码的主要功能是读取任何文件,把里面的内容都变成大写,然后把结果保存到一个新文件里,文件名是“UPPER”加上原文件名。不过,我想把“UPPER”这个部分加到文件名里,但不能放在最前面或最后面,因为这样会影响到文件的路径和扩展名。比如说,原文件是C:/users/me/directory/file.txt,处理后应该变成C:/users/me/directory/UPPERfile.txt。

2 个回答

1

可以看看 os.path.splitos.path.splitext 这两个方法,它们来自 os.path 模块。

另外,提醒一下:别忘了关闭你的“输入文件”。

0

根据你想要实现的具体方式,有几种不同的方法。

首先,你可能只想获取文件名,而不是整个路径。你可以使用 os.path.split 来做到这一点。

>>> pathname = r"C:\windows\system32\test.txt"
>>> os.path.split(pathname)
('C:\\windows\\system32', 'test.txt')

接下来,你还可以看看 os.path.splitext

>>> filename = "test.old.txt"
>>> os.path.splitext(filename)
('test.old', '.txt')

最后,字符串格式化也是个不错的选择。

>>> test_string = "Hello, {}"
>>> test_string.format("world") + ".txt"
"Hello, world.txt"

把这些结合起来,你可能会得到类似这样的结果:

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)

撰写回答