【问题标题】:How do I change the name of a file path correctly in Python?如何在 Python 中正确更改文件路径的名称?
【发布时间】:2014-05-19 23:33:43
【问题描述】:

我的代码

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

【问题讨论】:

标签: python filenames


【解决方案1】:

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

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

【讨论】:

    【解决方案2】:

    根据您尝试执行此操作的具体方式,有几种方法。

    首先,您可能只想获取文件名,而不是整个路径。使用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)
    

    【讨论】:

      猜你喜欢
      • 1970-01-01
      • 2020-12-23
      • 1970-01-01
      • 2012-02-02
      • 1970-01-01
      • 1970-01-01
      • 2017-04-13
      • 1970-01-01
      • 2021-06-23
      相关资源
      最近更新 更多