How does Python operate files and directories?
Python操作文件和目录
读写文件比较简单,有一点特别注意就好了
windows下Python默认打开的文件以gbk解码,而一般我们的文件是utf-8编码的,所以如果文本含有中文,就会出现异常或者乱码。此时手动添加encoding='utf-8'
表示以utf-8的方式打开。
当然Python写入时候,也是默认以gbk的编码写入。而文件通常是utf-8格式保存的,所以若不指定写入的编码方式,一写入中文就是乱码了
with open('abc.txt', encoding='utf-8') as f:print(f.read()) # 这样打开文件有中文也不怕# 当然Python写入时候,默认以gbk的编码写入。而文件是utf-8格式保存的,所以不指定写入的编码方式,一写入中文就是乱码了with open('abc.txt', 'w', encoding='utf-8') as f: f.write('你好')
好了进入正题
os模块
当前工作目录
下面的代码可获取/切换当前工作目录,也就是.
代表的路径
import osprint(os.getcwd()) # F:\PythonProjectos.chdir(r'D:\python')print(os.getcwd()) # D:\pythonprint(os.path.abspath('.')) # D:\python# 由于工作目录切换到D:\python,所以这个aa.txt就在其下生成with open('aa.txt', 'w', encoding='utf-8') as f: f.write('你好')
os.chdir
可以切换当前的工作目录,也就是改变了.
所指向的目录。于是相对路径aa.txt
就在切换后的路径下生成。这两个路径表达同一个意思
aa.txt
.\aa.txt
还有两个点,表示当前目录的父目录。..\aa.txt
这样就是D:\aa.txt
的意思了。
绝对路径和相对路径
绝对路径指的是从根文件夹子(盘符)开始
相对路径是相对于当前工作目录
print(os.path.abspath('aa.txt')) # D:\python\aa.txtprint(os.path.isabs('aa.txt')) # Falseprint(os.path.isabs('.')) #False
上面的代码,第一个函数返回参数路径的绝对路径,第二个函数用于检查一个路径是否是相对路径。
获取最后一个斜杠前后的路径。
# 获取最后一个斜杠后面的部分print(os.path.basename(r'D:\python\aa.txt')) # aa.txtprint(os.path.dirname(r'D:\python\aa.txt')) # D:\python# 当然使用下面的函数可以同时获得以上两者print(os.path.split(r'D:\python\aa.txt')) # ('D:\\python', 'aa.txt')
以其他方式分割
print(os.path.splitext(r'D:\python\aa.txt')) # ('D:\\python\\aa', '.txt')print(os.path.splitdrive(r'D:\python\aa.txt')) # ('D:', '\\python\\aa.txt')
os.path.splitext
这个函数以可以方便地获取文件后缀名,如果提供地路径是文件夹,那么返回空。
os.path.splitdrive
以盘符作为分隔。
注意,它们都返回元组。
检查路径
检查一个路径存不存在,是文件?还是文件夹?
print(os.path.isfile('D:\python')) # Falseprint(os.path.isdir('D:\python')) # Trueprint(os.path.exists('D:\python')) # True
创建文件夹
os.mkdir('D:\good') # True 只能建立一级不存在的目录,若已存在会报错os.mkdir('D:\good\job') # True 注释掉上一句,由于D:\good已经存在,这里相当于还是只新建了一级不存在的目录os.mkdir(r'D:\aa\bb') # 报错!!由于aa和bb文件夹都不存在,找不到D:\aa路径,故不能创建os.makedirs(r'D:\aa\bb') # 此函数没有上上面的限制,管他存不存在一股脑儿创建,反正最后会生成此路径就是了。不过如果此路径已经存在了,就会报错了
由此可以看出os.makedirs
更常用,可以创建处路径里所有的文件夹。而os.mkdir
还必须保证上级目录存在,所以只能新建一级目录。
连接路径
print(os.path.join(r'D:\python', 'aa.txt')) # D:\python\aa.txt
这个函数也很常用,用于连接两个路径,组合成新路径返回。
遍历文件夹
# 返回元组,分别是当前文件夹路径, 当前路径下的子文件夹,当前路径下的文件for current_path, subfolders, filesname in os.walk(r'D:\Cleaner'):print(f'{current_path}\n{subfolders}\n{filesname}')print('-'*30)
os.walk
可以递归遍历给定路径下所有地文件和文件夹。看下该目录下这个函数会打印什么。这个函数会返回一个元组,分别是(当前路径, 该路径下的所有文件夹, 该路径下的所有文件),然后不断递归深入,不断返回这样的元组。所以上面的for循环执行了多次,直到路径最深处。
D:\Cleaner ['CCleaner'] ['desktop.ini'] ------------------------------ D:\Cleaner\CCleaner ['Lang'] ['branding.dll', 'business.dat', 'CCleaner.dat', 'CCleaner.exe', 'ccleaner.ini', 'CCleaner64.exe', 'portable.dat'] ------------------------------ ....
删除文件/文件夹
# 永久删除,不进入回收站os.remove(r'D:\aaaa.txt') # same as os.unlink()# 目录为空才能删除, 只是删除当前文件夹os.rmdir(r'D:\aaa\bbb\ccc\eee')# 这个方法也不能删除非空目录,但是删除了空文件夹子eee后若发现父级文佳夹也空就一并删除os.removedirs(r'D:\aaa\bbb\ccc\eee') # 剩下D:\aaa\bbb# 强力,该目录下所有文件/文件夹全部删除,不管内容空不空。慎用shutil.rmtree(r'D:\aaa')
重命名
# 重命名文件夹,必须保证原路径存在,目标路径不能已存在os.rename(r'D:\python', 'D:\good')# 重命名文件,必须保证原路径存在,目标路径不能已存在os.rename(r'D:\good\aa.txt', r'D:\good\bb.txt')# 上面都不能再目标地址存在的情况下使用,这个函数粗暴,如果目标路径已存在,则会覆盖之,慎用os.replace(r'D:\good\bb.txt', r'D:\good\cc.txt')
获取文件的大小
得到文件的大小,以字节为单位
print(os.path.getsize(r'D:\good\cc.txt'))
shutil模块
os模块的功能相当强大,但是还有部分功能,比如复制/剪切文件和文件夹存在与shutil模块中。
直接看代码吧
copy
# 如果Movie目录存在,则是把这个文件复制到了该目录下。des1 = shutil.copy(r'D:\findall.txt', r'E:\Movie')# 如果没有该目录,则新建Mov文件,无后缀名des2= shutil.copy(r'D:\findall.txt', r'E:\Mov')# 当然指定了后缀名,就把源文件复制过去并重命名des2= shutil.copy(r'D:\findall.txt', r'E:\Mov.txt')# copy只复制最后访问时间des3 = shutil.copy(r'D:\findall.txt', r'E:\findit.txt')# copy2同时拷贝所有元数据包括修改时间和最后访问时间des4 = shutil.copy2(r'D:\findall.txt', r'E:\find.txt')# 不拷贝访问时间和修改时间des5 = shutil.copyfile(r'D:\findall.txt', r'E:\findaa.txt')# 可以看到返回的是新文件所在的路径print(f'{des1}\n{des2}\n{des3}')# 拷贝整个文件夹(里面所有内容)到另外一个文件夹,该文件夹不能是已经存在的文件夹shutil.copytree(r'D:\abc', r'E:\Movie')
move
# 剪切文件, abc不存在就移动文件并改名为abc, abc目录存在则放入该目录shutil.move(r'D:\findall.txt', r'E:\abc')# 目标地址若是文件,则是移动并重命名shutil.move(r'D:\findall.txt', r'E:\aa.txt')# 剪切文件夹,如果目标目录已经存在,则剪切并放入该目录,如果目标目录不存在,则相当于移动目录到目标地址并重命名文件夹shutil.move(r'D:\abc', r'E:\avb')
ok,对文件和目录的操作也是日常生活中经常会使用到的。学习了这些已经可以自动完成很多操作了。
by @sunhaiyu
2017.6.26
The above is the detailed content of How does Python operate files and directories?. For more information, please follow other related articles on the PHP Chinese website!

Hot AI Tools

Undresser.AI Undress
AI-powered app for creating realistic nude photos

AI Clothes Remover
Online AI tool for removing clothes from photos.

Undress AI Tool
Undress images for free

Clothoff.io
AI clothes remover

Video Face Swap
Swap faces in any video effortlessly with our completely free AI face swap tool!

Hot Article

Hot Tools

Notepad++7.3.1
Easy-to-use and free code editor

SublimeText3 Chinese version
Chinese version, very easy to use

Zend Studio 13.0.1
Powerful PHP integrated development environment

Dreamweaver CS6
Visual web development tools

SublimeText3 Mac version
God-level code editing software (SublimeText3)

Hot Topics

PHP is mainly procedural programming, but also supports object-oriented programming (OOP); Python supports a variety of paradigms, including OOP, functional and procedural programming. PHP is suitable for web development, and Python is suitable for a variety of applications such as data analysis and machine learning.

Python is more suitable for beginners, with a smooth learning curve and concise syntax; JavaScript is suitable for front-end development, with a steep learning curve and flexible syntax. 1. Python syntax is intuitive and suitable for data science and back-end development. 2. JavaScript is flexible and widely used in front-end and server-side programming.

PHP is suitable for web development and rapid prototyping, and Python is suitable for data science and machine learning. 1.PHP is used for dynamic web development, with simple syntax and suitable for rapid development. 2. Python has concise syntax, is suitable for multiple fields, and has a strong library ecosystem.

VS Code can run on Windows 8, but the experience may not be great. First make sure the system has been updated to the latest patch, then download the VS Code installation package that matches the system architecture and install it as prompted. After installation, be aware that some extensions may be incompatible with Windows 8 and need to look for alternative extensions or use newer Windows systems in a virtual machine. Install the necessary extensions to check whether they work properly. Although VS Code is feasible on Windows 8, it is recommended to upgrade to a newer Windows system for a better development experience and security.

VS Code can be used to write Python and provides many features that make it an ideal tool for developing Python applications. It allows users to: install Python extensions to get functions such as code completion, syntax highlighting, and debugging. Use the debugger to track code step by step, find and fix errors. Integrate Git for version control. Use code formatting tools to maintain code consistency. Use the Linting tool to spot potential problems ahead of time.

PHP originated in 1994 and was developed by RasmusLerdorf. It was originally used to track website visitors and gradually evolved into a server-side scripting language and was widely used in web development. Python was developed by Guidovan Rossum in the late 1980s and was first released in 1991. It emphasizes code readability and simplicity, and is suitable for scientific computing, data analysis and other fields.

In VS Code, you can run the program in the terminal through the following steps: Prepare the code and open the integrated terminal to ensure that the code directory is consistent with the terminal working directory. Select the run command according to the programming language (such as Python's python your_file_name.py) to check whether it runs successfully and resolve errors. Use the debugger to improve debugging efficiency.

VS Code extensions pose malicious risks, such as hiding malicious code, exploiting vulnerabilities, and masturbating as legitimate extensions. Methods to identify malicious extensions include: checking publishers, reading comments, checking code, and installing with caution. Security measures also include: security awareness, good habits, regular updates and antivirus software.
