【问题标题】:how can i change only the first letter of a filename into uppercase? [duplicate]如何仅将文件名的第一个字母更改为大写? [复制]
【发布时间】:2021-08-05 00:22:12
【问题描述】:
import os

def soldier(ppth):
            pth= os.listdir(ppth)
            for filename in pth:
                os.rename(filename,filename.lower())
            print(pth)
soldier("D://QwertyA")

【问题讨论】:

  • 即使我使用 os.rename(filename,filename.capitalize())。它产生一个错误 FileNotFoundError: [WinError 2] The system cannot find the file specified: 'asd.docx' -> 'Asd.docx'
  • 您可能需要使用文件f"{ppth}/{filename}"的完整路径

标签: python filenames


【解决方案1】:

你可以使用大写的方法。

string.capitalize()

def soldier(ppth):             
    pth= os.listdir(ppth)             
    for filename in pth:                 
        os.rename(f"{ppth}/{filename}",f"{ppth}/{filename.lower().capitalize()}")

【讨论】:

  • 不!我想将特定目录中存在的文件的第一个字母大写
  • 对。 import os def soldier(ppth): pth= os.listdir(ppth) for filename in pth: os.rename(filename,filename.lower().capitalize()) print(pth) soldier("D://QwertyA")
  • 这正是我想要的
【解决方案2】:

你可以试试这样的。

import os
fileName = 'test.txt'
newFileName = fileName.capitalize()
print(newFileName)
os.rename(f'/path/to/file/{fileName}',f'/path/to/file{newFileName}')

好像我的文件被大写了。

【讨论】:

    猜你喜欢
    • 2014-01-02
    • 2012-04-17
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 1970-01-01
    • 2013-06-22
    • 1970-01-01
    相关资源
    最近更新 更多