前言:数据处理时在遇到大量文件需要整理,为了使数据整齐化,需要对数据的名字进行重命名。笔者这里的需求是保留文件名中间的时间,用时间作为新的文件名。
一、目录操作
os.listdir():获取指定路径下的文件名称集合
def listdir(*args, **kwargs): # real signature unknown
"""
Return a list containing the names of the files in the directory.
path can be specified as either str, bytes, or a path-like object. If path is bytes,
the filenames returned will also be bytes; in all other circumstances
the filenames returned will be str.
If path is None, uses the path='.'.
On some platforms, path may also be specified as an open file descriptor;\
the file descriptor must refer to a directory.
If this functionality is unavailable, using it raises NotImplementedError.
The list is in arbitrary order. It does not include the special
entries '.' and '..' even if they are present in the directory.
"""
pass
验证:
二、路径分割
os.path.splitext(path)
import os
FileName = os.path.splitext("4120211123143292.mp4")[0]
ExtensionName = os.path.splitext("4120211123143292.mp4")[1]
print(FileName)
print(ExtensionName)
输出
D:\Anaconda3\envs\Python\python.exe G:/Git/Python/Python/komla/os.path.splitext.py
4120211123143292
.mp4
Process finished with exit code 0
说明:如果path是带有扩展名的文件名称,会把文件名和扩展名分开,索引0是文件名,索引1是扩展名。还有一个os.path.split(path)函数,更详细的介绍看这篇文章os.path.splitext(file) 和 os.path.split(file) - 知乎
(根据上面大佬的实验,个人感觉内部是根据'.'和'/'进行分割的,有兴趣的小伙伴可以试下)
三、重命名
os.rename(src,dst):重命名文件或目录
def rename(*args, **kwargs): # real signature unknown
"""
Rename a file or directory.
If either src_dir_fd or dst_dir_fd is not None, it should be a file
descriptor open to a directory, and the respective path string (src or dst)
should be relative; the path will then be relative to that directory.
src_dir_fd and dst_dir_fd, may not be implemented on your platform.
If they are unavailable, using them will raise a NotImplementedError.
"""
pass
这里的参数:src和dst是路径,笔者开始网搜了一段代码,报错,
D:\Anaconda3\envs\Python\python.exe G:/Git/Python/Python/komla/RenameFile.py
Traceback (most recent call last):
File "G:\Git\Python\Python\komla\RenameFile.py", line 10, in <module>
os.rename(file, new) # 进行重命名
FileNotFoundError: [WinError 2] 系统找不到指定的文件。: '20220224_141921.jpg' -> '1921.jpg.jpg'
['20220224_141921.jpg', '20220224_141923.jpg', '20220224_141952.jpg', '20220224_141954.jpg', '20220224_141955.jpg', '20220224_141957.jpg', '20220224_141958.jpg', '20220224_142001.jpg', '20220224_142004.jpg', '20220224_142018.jpg']
Process finished with exit code 1
因为通过os.listdir()获取的目录路径下的文件名,对原文件名重命名后直接将其放入os.rename(src,dst)不可以,因为没有路径,系统找不到,不知道是不是笔者的问题,反正是报错了,有大神有知道的可以留言告知。
四、代码
import os
curpath = r'F:\test\pic'
dir = os.listdir(curpath)
for file in dir:
if os.path.splitext(file)[1] == '.jpg':
new = file[11:26] + '.jpg'
os.rename(curpath+'\\' + file, curpath+'\\' + new)
print(os.listdir(curpath))
说明:
获取路径下的文件,然后判断下后缀名(也可以是.png的),设置重命名后的文件名,调用rename重命名。这里new后面需要把扩展名带上,不然重命名后没有扩展名,还有rename里面就是前面提到的,要是一个带有路径的完整的路径,比如F:\test\pic\20220302.jpg,不然就会报错