> For the complete documentation index, see [llms.txt](https://kawsing.gitbook.io/opensystem/llms.txt). Markdown versions of documentation pages are available by appending `.md` to page URLs; this page is available as [Markdown](https://kawsing.gitbook.io/opensystem/yun-suan-si-wei/python-install-on-windows/gong-ju-rename.md).

# 工具:rename

windows 的\ 會出現的問題

**SyntaxError: (unicode error) 'unicodeescape' codec can't decode bytes in position 2-3: truncated \UXXXXXXXX escape**<br>

```
#-*- coding: utf-8 -*-　　 
#-*- coding: cp950 -*-
import os
#使用這個
'''old_file_name = "C:\\Users\\user\\Downloads\\old.txt"

new_file_name = "C:\\Users\\user\\Downloads\\new.txt" '''
#或用這個
old_file_name = r"C:\Users\user\Downloads\old.txt"
new_file_name = r"C:\Users\user\Downloads\new.txt"
os.rename(old_file_name, new_file_name)

print("File renamed!")
```

拆解副檔名(extension)

```
>>> import os
>>> filename, file_extension = os.path.splitext('/path/to/somefile.ext')
>>> filename
'/path/to/somefile'
>>> file_extension
'.ext'
#與大多數手動字符串拆分嘗試不同，os.path.splitext它將正確地/a/b.c/d視為沒有擴展而不是具有extension .c/d，並且將被.bashrc視為沒有擴展而不是具有extension .bashrc：

>>> os.path.splitext('/a/b.c/d')
('/a/b.c/d', '')
>>> os.path.splitext('.bashrc')
('.bashrc', '')
```

簡易批次改名工具

```
#-*- coding: utf-8 -*-　　 
#-*- coding: cp950 -*-
import os


def batch_rename(path):
    count = 0
    for fname in os.listdir(path):
        new_fname = str(count)
        file=os.path.join(path, fname)
        fname, fext = os.path.splitext(file)
        os.rename(os.path.join(path, fname + fext), os.path.join(path, new_fname + fext))
        count = count + 1
dir = input("請輸入資料夾路徑:")
batch_rename(dir)
```
