python 目录和文件基本操作

目录操作

获取当前目录:
import os
dir_path = os.getcwd()
print("当前目录:", dir_path)

当前目录: D:\work\pycharm\object

创建目录:
import os

dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")
if not os.path.exists(new_dir):
    os.makedirs(new_dir)
    print(f"目录 '{new_dir}' 创建成功")
else:
    print(f"目录 '{new_dir}' 已经存在,跳过创建")

目录 'D:\work\pycharm\object\test_dir' 已经存在,跳过创建

文件操作

创建文件:
import os
dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")
new_file_path = os.path.join(new_dir, "test.txt")
print(new_file_path)
with open(new_file_path, 'w') as f:
    f.write("hello txt")
    f.close()

D:\work\pycharm\object\test_dir\test.txt

批量创建:
import os
import datetime

dir_path = os.getcwd()
print("当前目录:", dir_path)

new_dir = os.path.join(dir_path, "test_dir")

current_year_month = datetime.datetime.now().strftime("%Y-%m")
print("当前年月是:", current_year_month)

""" 当前年月是: 2024-03 """



for i in range(1, 10):
    new_datetime = current_year_month + '-' + str(i)
    new_file_path = os.path.join(new_dir, f"test{new_datetime}.txt")
    with open(new_file_path, 'w') as f:
        f.write("hello")
        f.close()

批量读取:
print(new_dir)
file_path = os.listdir(new_dir)
print(file_path)
for file_name in file_path:
    # 只处理文件结尾是txt的
    if file_name.endswith(".txt"):
        file_path = os.path.join(new_dir, file_name)
        with open(file_path, 'r') as f:
            f_content = f.read()
            print(f"{file_name}的内容是{f_content}")

打开文件:

如果报错编码问题的话,就在open里面加上  encoding='utf-8'

file_path = '/opt/pytest/file/信息笔记.txt'



#打开文件,只读模式

with open(file_path,'r') as file:

#读取文件内容

        file_content = file.read()

        print(file_content)
向文件追加内容:
with open(new_file_path, 'a') as f:
    f.write("追加数据:hello python" + "\n")
with open(new_file_path, 'r') as f:
    f_content = f.read()
    print(f_content)

excel操作

读取文件
# 读取excel表格内容
import pandas as pd
excel_file_path = r'D:\桌面\运维分工表.xlsx'
# 读取 Excel 文件
df = pd.read_excel(excel_file_path, sheet_name='运维分工')

# print(df.head())
print(df)
写入excel文件
# 将数据写入excel
import openpyxl
wb = openpyxl.Workbook()
sheet = wb.active

sheet['A1'] = '姓名'
sheet['B1'] = '年龄'
sheet['A2'] = '张三'
sheet['B2'] = 25
sheet['A3'] = '李四'
sheet['B3'] = 30

# 保存工作簿到文件
wb.save('人员信息描述.xlsx')

  • 6
    点赞
  • 5
    收藏
    觉得还不错? 一键收藏
  • 0
    评论

“相关推荐”对你有帮助么?

  • 非常没帮助
  • 没帮助
  • 一般
  • 有帮助
  • 非常有帮助
提交
评论
添加红包

请填写红包祝福语或标题

红包个数最小为10个

红包金额最低5元

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

抵扣说明:

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

余额充值