python中的os模块的基础用法
时间: 2023-09-27 09:08:38 浏览: 91
os模块是Python中用于操作文件和目录的标准库。下面是os模块的一些基础用法:
1. 获取当前工作目录
```python
import os
cwd = os.getcwd()
print(cwd)
```
2. 改变工作目录
```python
import os
os.chdir('/path/to/new/directory')
```
3. 获取指定目录下的所有文件和目录
```python
import os
path = '/path/to/directory'
files = os.listdir(path)
print(files)
```
4. 创建目录
```python
import os
os.mkdir('/path/to/new/directory')
```
5. 删除目录
```python
import os
os.rmdir('/path/to/directory')
```
6. 获取文件大小
```python
import os
size = os.path.getsize('/path/to/file')
print(size)
```
7. 删除文件
```python
import os
os.remove('/path/to/file')
```
8. 判断文件或目录是否存在
```python
import os
if os.path.exists('/path/to/file'):
# do something
else:
# do something else
```
以上是os模块的一些基础用法,更多用法可以查看Python官方文档。
阅读全文
相关推荐
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![doc](https://img-home.csdnimg.cn/images/20241231044833.png)
![docx](https://img-home.csdnimg.cn/images/20241231044901.png)
![rar](https://img-home.csdnimg.cn/images/20241231044955.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![](https://csdnimg.cn/download_wenku/file_type_ask_c1.png)
![pdf](https://img-home.csdnimg.cn/images/20241231044930.png)