我编写了这个程序来将目录中的所有文件重命名为标题大小写,并且它在系统上的文件上工作正常。但是当我用它来重命名外部驱动器上的文件时,程序成功执行,没有任何异常,但文件名保持不变。
# Import the os and shutil modules to interact with the operating system and files
import os
import shutil
def main():
try:
print("This program will rename all the files in the specified directory to title case.")
dir_path = input("Enter the directory: ").strip() # Ask the user to enter the directory path
if os.path.isdir(dir_path): # Check if the entered path is a valid directory
dir_path = os.path.join(dir_path, "") # Add a trailing slash to the path for later use
else:
raise Exception("Invalid path.") # Raise an exception if it's not a valid directory
for item in os.listdir(dir_path): # Iterate over all the items in the specified directory
if os.path.isdir(item):
continue # Skip if the item is a directory
filename, extension = os.path.splitext(item) # Separate the filename and extension
filename = filename.title() # Convert the filename to title case
destination = os.path.join(dir_path, filename + extension) # Create path with the new filename
shutil.move(os.path.join(dir_path, item), destination) # Rename the file
print("Operation Successful!")
except Exception as e:
print(e) # If there's an error, print the error message
if __name__ == "__main__":
main()
我也尝试过使用
os.rename()
功能,它没有用所以这是第二次尝试。也试过在 linux 系统中运行这个程序,没有用。问 ChatGPT,它说在 for 循环之前添加os.chdir(dir_path)
,也没有用。帮我解决一下?
更新:正如 Saxtheowl 在对他的回答的评论 中所说,程序无法在外部驱动器上运行的问题在于文件系统。我的驱动器之前是 exFAT,尝试将文件系统更改为 NTFS,程序运行正常。询问 ChatGPT,它说:
exFAT 的一个限制是它不支持所有相同的 NTFS 文件操作,例如某些类型的文件权限和 文件属性。这可能会在尝试执行某些操作时导致问题 文件操作,例如重命名文件或复制文件 属性。
在你的情况下,重命名程序的问题可能不是 在 exFAT 驱动器上工作是由于文件的限制 系统,例如最大文件名长度或缺乏支持 对于某些文件属性。将文件系统更改为 NTFS 会 允许程序正常工作,因为 NTFS 支持更广泛的 文件操作范围,限制更少。
您的
os.path.isdir(item)
失败,因为 item
仅包含文件的基本名称,并且函数需要完整路径。您应该改用os.path.join(dir_path, item)
,这是修改后的代码:
import os
import shutil
def main():
try:
print("This program will rename all the files in the specified directory to title case.")
dir_path = input("Enter the directory: ").strip()
if os.path.isdir(dir_path):
dir_path = os.path.join(dir_path, "")
else:
raise Exception("Invalid path.")
for item in os.listdir(dir_path):
item_path = os.path.join(dir_path, item) # Create the full path for the item
if os.path.isdir(item_path): # Check if the item is a directory using the full path
continue
filename, extension = os.path.splitext(item)
filename = filename.title()
destination = os.path.join(dir_path, filename + extension)
shutil.move(item_path, destination)
print("Operation Successful!")
except Exception as e:
print(e)
if __name__ == "__main__":
main()