Python的文件操作 新手必看2020最新

####相对路径

相对于当前写代码 的文件所在的文件夹,    是当前文件夹
f1 = open("./123.txt", "r", encoding="utf-8")
content = f1.read()
print(content)
f1.close()

f1 = open("./hehe/haha.txt", "r", encoding="utf-8")

#  ..表示当前当前写代码的文件上一层文件夹
f1 = open("../test/test1.txt", "r", encoding="utf-8")

# ..表示当前当前写代码的文件上一层文件夹
f1 = open("../../testtest/test1.txt", "r", encoding="utf-8")
#   绝对路径
f1 = open('C:/Users/halon/Desktop/python基础/testtest/test1.txt', 'r', encoding='utf-8')

### 2. 文件夹的操作

import os

#### 文件夹   directory

# 原文件名  新文件名
os.rename("123.txt", "321.txt")

# 删除文件
os.remove("123.txt")

# 创建文件夹
os. mkdir ("music")

os.rmdir("music")   # rmdir 只能删除空文件夹
os.rmdir("hehe")     # 删除不了

# 获取指定目录下的文件目录,   包含隐藏文件
os.listdir("./")
os.listdir("c:./")

# 当前目录的绝对路径
os.getcwd()

#  修改 默认目录到hehe文件夹  , 不要经常用
os.chdir("./hehe")
# 修改后 相对路径就是hehe 文件夹了
open("hehe.txt", "w")

# 判断是不是一个文件夹.py
os.path.isdir("xioashuo")    #True
os.path.isdir("123.txt")  # False 

####文件的路径
  • 0
    点赞
  • 0
    收藏
    觉得还不错? 一键收藏
  • 0
    评论
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

当前余额3.43前往充值 >
需支付:10.00
成就一亿技术人!
领取后你会自动成为博主和红包主的粉丝 规则
hope_wisdom
发出的红包
实付
使用余额支付
点击重新获取
扫码支付
钱包余额 0

抵扣说明:

1.余额是钱包充值的虚拟货币,按照1:1的比例进行支付金额的抵扣。
2.余额无法直接购买下载,可以购买VIP、付费专栏及课程。

余额充值