Table of Contents
Python操作文件和目录
os模块
当前工作目录
绝对路径和相对路径
检查路径
创建文件夹
连接路径
遍历文件夹
删除文件/文件夹
重命名
获取文件的大小
shutil模块
copy
move
Home Backend Development Python Tutorial How does Python operate files and directories?

How does Python operate files and directories?

Jun 27, 2017 am 09:55 AM
python operate document Table of contents

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('你好')
Copy after login

好了进入正题

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('你好')
Copy after login

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
Copy after login

上面的代码,第一个函数返回参数路径的绝对路径,第二个函数用于检查一个路径是否是相对路径。

获取最后一个斜杠前后的路径。

# 获取最后一个斜杠后面的部分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')
Copy after login

以其他方式分割

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')
Copy after login

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
Copy after login

创建文件夹

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')  # 此函数没有上上面的限制,管他存不存在一股脑儿创建,反正最后会生成此路径就是了。不过如果此路径已经存在了,就会报错了
Copy after login

由此可以看出os.makedirs更常用,可以创建处路径里所有的文件夹。而os.mkdir还必须保证上级目录存在,所以只能新建一级目录。

连接路径

print(os.path.join(r'D:\python', 'aa.txt')) # D:\python\aa.txt
Copy after login

这个函数也很常用,用于连接两个路径,组合成新路径返回。

遍历文件夹

# 返回元组,分别是当前文件夹路径, 当前路径下的子文件夹,当前路径下的文件for current_path, subfolders, filesname in os.walk(r'D:\Cleaner'):print(f'{current_path}\n{subfolders}\n{filesname}')print('-'*30)
Copy after login

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']
------------------------------
....
Copy after login

删除文件/文件夹

# 永久删除,不进入回收站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')
Copy after login

重命名

# 重命名文件夹,必须保证原路径存在,目标路径不能已存在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')
Copy after login

获取文件的大小

得到文件的大小,以字节为单位

print(os.path.getsize(r'D:\good\cc.txt'))
Copy after login

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')
Copy after login

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')
Copy after login

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!

Statement of this Website
The content of this article is voluntarily contributed by netizens, and the copyright belongs to the original author. This site does not assume corresponding legal responsibility. If you find any content suspected of plagiarism or infringement, please contact admin@php.cn

Hot AI Tools

Undresser.AI Undress

Undresser.AI Undress

AI-powered app for creating realistic nude photos

AI Clothes Remover

AI Clothes Remover

Online AI tool for removing clothes from photos.

Undress AI Tool

Undress AI Tool

Undress images for free

Clothoff.io

Clothoff.io

AI clothes remover

AI Hentai Generator

AI Hentai Generator

Generate AI Hentai for free.

Hot Article

R.E.P.O. Energy Crystals Explained and What They Do (Yellow Crystal)
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. Best Graphic Settings
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
R.E.P.O. How to Fix Audio if You Can't Hear Anyone
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌
WWE 2K25: How To Unlock Everything In MyRise
3 weeks ago By 尊渡假赌尊渡假赌尊渡假赌

Hot Tools

Notepad++7.3.1

Notepad++7.3.1

Easy-to-use and free code editor

SublimeText3 Chinese version

SublimeText3 Chinese version

Chinese version, very easy to use

Zend Studio 13.0.1

Zend Studio 13.0.1

Powerful PHP integrated development environment

Dreamweaver CS6

Dreamweaver CS6

Visual web development tools

SublimeText3 Mac version

SublimeText3 Mac version

God-level code editing software (SublimeText3)

Do mysql need to pay Do mysql need to pay Apr 08, 2025 pm 05:36 PM

MySQL has a free community version and a paid enterprise version. The community version can be used and modified for free, but the support is limited and is suitable for applications with low stability requirements and strong technical capabilities. The Enterprise Edition provides comprehensive commercial support for applications that require a stable, reliable, high-performance database and willing to pay for support. Factors considered when choosing a version include application criticality, budgeting, and technical skills. There is no perfect option, only the most suitable option, and you need to choose carefully according to the specific situation.

How to use mysql after installation How to use mysql after installation Apr 08, 2025 am 11:48 AM

The article introduces the operation of MySQL database. First, you need to install a MySQL client, such as MySQLWorkbench or command line client. 1. Use the mysql-uroot-p command to connect to the server and log in with the root account password; 2. Use CREATEDATABASE to create a database, and USE select a database; 3. Use CREATETABLE to create a table, define fields and data types; 4. Use INSERTINTO to insert data, query data, update data by UPDATE, and delete data by DELETE. Only by mastering these steps, learning to deal with common problems and optimizing database performance can you use MySQL efficiently.

MySQL can't be installed after downloading MySQL can't be installed after downloading Apr 08, 2025 am 11:24 AM

The main reasons for MySQL installation failure are: 1. Permission issues, you need to run as an administrator or use the sudo command; 2. Dependencies are missing, and you need to install relevant development packages; 3. Port conflicts, you need to close the program that occupies port 3306 or modify the configuration file; 4. The installation package is corrupt, you need to download and verify the integrity; 5. The environment variable is incorrectly configured, and the environment variables must be correctly configured according to the operating system. Solve these problems and carefully check each step to successfully install MySQL.

MySQL download file is damaged and cannot be installed. Repair solution MySQL download file is damaged and cannot be installed. Repair solution Apr 08, 2025 am 11:21 AM

MySQL download file is corrupt, what should I do? Alas, if you download MySQL, you can encounter file corruption. It’s really not easy these days! This article will talk about how to solve this problem so that everyone can avoid detours. After reading it, you can not only repair the damaged MySQL installation package, but also have a deeper understanding of the download and installation process to avoid getting stuck in the future. Let’s first talk about why downloading files is damaged. There are many reasons for this. Network problems are the culprit. Interruption in the download process and instability in the network may lead to file corruption. There is also the problem with the download source itself. The server file itself is broken, and of course it is also broken when you download it. In addition, excessive "passionate" scanning of some antivirus software may also cause file corruption. Diagnostic problem: Determine if the file is really corrupt

Solutions to the service that cannot be started after MySQL installation Solutions to the service that cannot be started after MySQL installation Apr 08, 2025 am 11:18 AM

MySQL refused to start? Don’t panic, let’s check it out! Many friends found that the service could not be started after installing MySQL, and they were so anxious! Don’t worry, this article will take you to deal with it calmly and find out the mastermind behind it! After reading it, you can not only solve this problem, but also improve your understanding of MySQL services and your ideas for troubleshooting problems, and become a more powerful database administrator! The MySQL service failed to start, and there are many reasons, ranging from simple configuration errors to complex system problems. Let’s start with the most common aspects. Basic knowledge: A brief description of the service startup process MySQL service startup. Simply put, the operating system loads MySQL-related files and then starts the MySQL daemon. This involves configuration

Does mysql need the internet Does mysql need the internet Apr 08, 2025 pm 02:18 PM

MySQL can run without network connections for basic data storage and management. However, network connection is required for interaction with other systems, remote access, or using advanced features such as replication and clustering. Additionally, security measures (such as firewalls), performance optimization (choose the right network connection), and data backup are critical to connecting to the Internet.

How to optimize MySQL performance for high-load applications? How to optimize MySQL performance for high-load applications? Apr 08, 2025 pm 06:03 PM

MySQL database performance optimization guide In resource-intensive applications, MySQL database plays a crucial role and is responsible for managing massive transactions. However, as the scale of application expands, database performance bottlenecks often become a constraint. This article will explore a series of effective MySQL performance optimization strategies to ensure that your application remains efficient and responsive under high loads. We will combine actual cases to explain in-depth key technologies such as indexing, query optimization, database design and caching. 1. Database architecture design and optimized database architecture is the cornerstone of MySQL performance optimization. Here are some core principles: Selecting the right data type and selecting the smallest data type that meets the needs can not only save storage space, but also improve data processing speed.

How to optimize database performance after mysql installation How to optimize database performance after mysql installation Apr 08, 2025 am 11:36 AM

MySQL performance optimization needs to start from three aspects: installation configuration, indexing and query optimization, monitoring and tuning. 1. After installation, you need to adjust the my.cnf file according to the server configuration, such as the innodb_buffer_pool_size parameter, and close query_cache_size; 2. Create a suitable index to avoid excessive indexes, and optimize query statements, such as using the EXPLAIN command to analyze the execution plan; 3. Use MySQL's own monitoring tool (SHOWPROCESSLIST, SHOWSTATUS) to monitor the database health, and regularly back up and organize the database. Only by continuously optimizing these steps can the performance of MySQL database be improved.

See all articles