python自动化办公数据分析的文件和目录操作

2022-08-21 10:06:21

使用os库
os库是Python标准库,随Python一起安装,无须单独安装。os是operation system(操作系统)的缩写,os库提供了使用各种操作系统功能的接口。os库中包含很多操作文件和目录的函数,可以方便地进行重命名文件、添加/删除目录、复制目录/文件等操作。
1.主要操作方法
导入os库。>>> import os
>>> dir(os)
运行后将显示os库包含的类、属性和函数,主要包括:abc、abort、access、altsep、chdir、chmod、close、closerange、cpu_count、curdir、defpath、device_encoding、devnull、dup、dup2、environ、error、execl、execle、execlp、execlpe、execv、execve、execvp、execvpe、extsep、fdopen、fsdecode、fsencode、fspath、fstat、fsync、ftruncate、get_exec_path、get_handle_inheritable、get_inheritable、get_terminal_size、getcwd、getcwdb、getenv、getlogin、getpid、getppid、isatty、kill、linesep、link、listdir、lseek、lstat、makedirs、mkdir、name、open、pardir、path、pathsep、pipe、popen、putenv、read、readlink、remove、removedirs、rename、renames、replace、rmdir、scandir、sep、set_handle_inheritable、set_inheritable、spawnl、spawnle、spawnv、spawnve、st、startfile、stat、stat_result、statvfs_result、strerror、supports_bytes_environ、supports_dir_fd、supports_effective_ids、supports_fd、supports_follow_symlinks、symlink、sys、system、terminal_size、times、times_result、truncate、umask、uname_result、unlink、urandom、utime、waitpid、walk、write。
函数说明
getcwd
获取当前工作目录,即当前Python脚本所在的目录路径
listdir
列出指定目录下的所有文件和子目录,包括隐藏文件
mkdir
创建目录
unlink
删除文件
remove
删除文件
rmdir
删除空目录
removedirs
若目录为空,则删除,并递归到上一级目录,若上一级目录为空,也删除
rename
重命名文件
stat
获取一个文件的属性及状态信息

使用os.path可以调用ntpath.py模块。>>> os.path
<module ‘ntpath’ from ‘C:\ProgramData\Anaconda3\lib\ntpath.py’>
通过dir函数查看ntpath.py模块中包含文件路径操作的函数,主要包括:abspath、altsep、basename、commonpath、commonprefix、curdir、defpath、devnull、dirname、exists、expanduser、expandvars、extsep、genericpath、getatime、getctime、getmtime、getsize、isabs、isdir、isfile、islink、ismount、join、lexists、normcase、normpath、os、pardir、pathsep、realpath、relpath、samefile、sameopenfile、samestat、sep、split、splitdrive、splitext、stat、supports_unicode_filenames、sys。
其中常用的操作函数有
函数
说明
abspath
返回规范化的绝对路径
basename
返回最后的文件名部分
dirname
返回目录部分
split
将文件名分割成目录和文件名
splitext
分离扩展名
join
将多个路径组合起来,以字符串中含有/的第一个路径开始拼接
getctime
返回文件或者目录的创建(复制到某个目录)的时间
getatime
访问时间,读一次文件的内容,这个时间就会更新
getmtime
修改时间,修改一次文件的内容,这个时间就会更新
getsize
获取文件大小
isabs
如果path是绝对路径,返回True
exists
如果path存在,则返回True;如果path不存在,则返回False
isdir
如果path是一个存在的目录,则返回True,否则返回False
isfile
如果path是一个存在的文件,则返回True,否则返回False

  • 作者:视觉震撼
  • 原文链接:https://blog.csdn.net/wddxwdwl/article/details/121027536
    更新时间:2022-08-21 10:06:21