python编程怎么改文件名

时间:2025-03-04 16:21:22 明星趣事

在Python中修改文件名,你可以使用`os`模块来执行一系列操作。下面是一个简单的步骤说明和代码示例,用于批量修改文件名。

步骤说明

导入os模块:

首先,你需要导入`os`模块,这是Python中处理文件和目录操作的标准库。

获取文件列表:

使用`os.listdir()`函数获取指定目录下的所有文件和文件夹的名称列表。

遍历文件列表:

通过循环遍历文件列表,对每个文件执行重命名操作。

重命名文件:

在循环中,使用`os.rename()`函数将文件重命名为新的名称。你可以根据需要自定义重命名的规则。

代码示例

下面是一个简单的Python脚本,用于给指定目录下的所有`.txt`文件添加`.log`后缀:

```python

import os

获取当前目录下的所有文件和文件夹

file_list = os.listdir('.')

遍历文件列表

for file in file_list:

检查文件是否以.txt结尾

if file.endswith('.txt'):

获取文件名和扩展名

file_name, file_extension = os.path.splitext(file)

构建新的文件名(添加.log后缀)

new_file = file_name + '.log'

重命名文件

os.rename(file, new_file)

print(f'已重命名: {file} -> {new_file}')

```

如果你想要更复杂的重命名规则,比如添加前缀或者替换文件名中的某些字符,你可以修改代码来实现这些需求。例如,给所有文件添加前缀`prefix_`:

```python

import os

prefix = "prefix_"

获取当前目录下的所有文件和文件夹

file_list = os.listdir('.')

遍历文件列表

for file in file_list:

构建新的文件名(添加前缀)

new_file = prefix + file

重命名文件

os.rename(file, new_file)

print(f'已重命名: {file} -> {new_file}')

```

或者替换文件名中的特定字符,比如将`old_str`替换为`new_str`:

```python

import os

def batch_rename(path, old_str, new_str):

获取目录下所有文件

file_list = os.listdir(path)

遍历处理每个文件

for old_name in file_list:

判断是否包含要替换的字符串

if old_str in old_name:

生成新文件名

new_name = old_name.replace(old_str, new_str)

拼接完整路径

old_file = os.path.join(path, old_name)

new_file = os.path.join(path, new_name)

重命名文件

os.rename(old_file, new_file)

print(f'已将 {old_name} 重命名为 {new_name}')

示例用法

folder_path = 'D:/test_files'

batch_rename(folder_path, '旧字符', '新字符')

```

在使用这些脚本时,请确保你有足够的权限来修改目标目录中的文件,并且注意备份重要数据以防万一。