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

时间:2014-05-19 23:33:44

标签: python filenames

我的代码

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“filename”的新文件中。如何将“UPPER”位添加到变量中而不是在最后或最开始?由于开头的其余文件路径和结尾的文件扩展名,它不会像那样工作。例如,C:/users/me/directory/file.txt将变为C:/users/me/directory/UPPERfile.txt

2 个答案:

答案 0 :(得分:1)

查看os.path模块中的方法os.path.splitos.path.splitext

另外,快速提醒:不要忘记关闭你的“infile”。

答案 1 :(得分: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)